1using Microsoft.AspNetCore.Mvc;2using QuickMaster.Models;3using System.Collections.Generic;using System.Linq;45namespace WebApplication1.Controllers
6{7 public class HomeController : Controller
8{9 private readonly MyContext _context;1011 public HomeController(MyContext context)12{13 this._context = context;14}1516 public ActionResult Index()17{1819 var query1 =(from m in _context.Trader select m).ToList();20 var query2 =(from n in _context.ItemList select n).ToList();2122 var result = query1.GroupJoin(23 query2,24 x => x.id,25 y => y.id,26(s, t)=>27 new { t }).ToList();28returnView();29}30}31}
1var query =2 from trader in traders
3 from item in items
4 where
5 trader.Id == item.Id &&6 item.ExpiryDate > new DateTime(2010,1,1)7 select new {8 Id = trader.Id,9 CompanyNm = trader.CompanyNm,10 Address = trader.Address,11 Price = item.Price,12 ExpireDate = item.ExpiryDate
13};1415var result = query.ToList();
1using System;2using System.Linq;34namespace LinqSample {5 class Program {6staticvoidMain(string[] args){7 var traders = new Trader[]{8 new Trader(){ Id =1, CompanyNm ="株式会社ABC", Address ="北海道"},9 new Trader(){ Id =2, CompanyNm ="株式会社DEF", Address ="青森"},10 new Trader(){ Id =3, CompanyNm ="株式会社GHI", Address ="秋田"},11 new Trader(){ Id =4, CompanyNm ="株式会社HIJ", Address ="岩手"},12 new Trader(){ Id =5, CompanyNm ="株式会社KLM", Address ="山形"},13 new Trader(){ Id =6, CompanyNm ="株式会社OPQ", Address ="宮城"},14};1516 var items = new ItemList[]{17 new ItemList(){ Id =1, Price =100, ExpiryDate = new DateTime(2000,4,1)},18 new ItemList(){ Id =2, Price =200, ExpiryDate = new DateTime(2005,5,1)},19 new ItemList(){ Id =3, Price =300, ExpiryDate = new DateTime(2010,6,1)},20 new ItemList(){ Id =4, Price =400, ExpiryDate = new DateTime(2015,7,1)},21 new ItemList(){ Id =5, Price =2020, ExpiryDate = new DateTime(2020,8,1)}22};2324 var result = traders.GroupJoin(25 items,26 trader => trader.Id,27 item => item.Id,28(trader, item)=> new { trader, item })29// シーケンスの展開30.SelectMany(traderAndItem => traderAndItem.item,(trader, item)=> new {31 Id = trader.trader.Id,32 CompanyNm = trader.trader.CompanyNm,33 Address = trader.trader.Address,34 Price = item.Price,35 ExpireDate = item.ExpiryDate
36})37.Where(o => o.ExpireDate > new DateTime(2010,1,1))38.ToList();3940foreach(var o in result){41 Console.WriteLine($"Id={o.Id}, CompanyNm={o.CompanyNm}, Address={o.Address}, Price={o.Price}, ExpireDate={o.ExpireDate}");42}43}44}4546 class Trader {47 public int Id { get; set;}48 public string CompanyNm { get; set;}49 public string Address { get; set;}50}5152 class ItemList {53 public int Id { get; set;}54 public int Price { get; set;}55 public DateTime ExpiryDate { get; set;}56}57}5859
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/10/22 03:05
2021/10/22 13:45