iT邦幫忙

0

linq or ef語法問題

  • 分享至 

  • xImage

想請教一個問題,如下圖

https://ithelp.ithome.com.tw/upload/images/20181124/201101252gmi4PmZn3.png

如果我要把City和Town group起來,並且以Create_Time來判斷最近的時間,想請問linq怎麼寫,lambda也可以

結果如下圖

https://ithelp.ithome.com.tw/upload/images/20181124/20110125Q4AEcWX9Yo.png

謝謝各位

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

5
暐翰
iT邦大師 1 級 ‧ 2018-11-24 22:33:21
最佳解答

2018-11-24.22.32.54-image.png

你先看一下,假如有需要補充說明的地方跟我說
另外,建議下一次能把測試資料轉成Json或是csv,讓有心的回答者方便測試

LINQPad Code:

void Main()
{
	#region 測試資料
	var json = @"
[
  {
    ""No"": ""01"",
    ""Name"": ""香蕉"",
    ""City"": ""台中"",
    ""Town"": ""霧峰"",
    ""Create_Time"": ""2018/11/24 12:00:00""
  },
  {
    ""No"": ""02"",
    ""Name"": ""蘋果"",
    ""City"": ""台中"",
    ""Town"": ""霧峰"",
    ""Create_Time"": ""2018/11/20 12:00:00""
  },
  {
    ""No"": ""03"",
    ""Name"": ""冰梨"",
    ""City"": ""台中"",
    ""Town"": ""霧峰"",
    ""Create_Time"": ""2018/11/15 12:00:00""
  },
  {
    ""No"": ""04"",
    ""Name"": ""番茄"",
    ""City"": ""南投"",
    ""Town"": ""草屯"",
    ""Create_Time"": ""2018/11/23 12:00:00""
  },
  {
    ""No"": ""05"",
    ""Name"": ""輯麴"",
    ""City"": ""南投"",
    ""Town"": ""草屯"",
    ""Create_Time"": ""2018/10/01 12:00:00""
  },
  {
    ""No"": ""06"",
    ""Name"": ""冰蜜桃 "",
    ""City"": ""南投"",
    ""Town"": ""草屯"",
    ""Create_Time"": ""2018/10/18 12:00:00""
  },
  {
    ""No"": ""07"",
    ""Name"": ""西衣"",
    ""City"": ""苗栗"",
    ""Town"": ""大湖"",
    ""Create_Time"": ""2018/11/05 12:00:00""
  },
  {
    ""No"": ""08"",
    ""Name"": ""草莓"",
    ""City"": ""苗栗"",
    ""Town"": ""大湖"",
    ""Create_Time"": ""2018/11/24 12:00:00""
  },
  {
    ""No"": ""09"",
    ""Name"": ""芭樂"",
    ""City"": ""苗栗"",
    ""Town"": ""大湖"",
    ""Create_Time"": ""2018/10/9 12:00:00""
  }
]
	";
	#endregion
	var testDatas = JsonConvert.DeserializeObject<List<Test>>(json);
	var result = testDatas.GroupBy(g => new { g.City, g.Town })
		.Select(s => new { s.Key, Datas = s.Where(w2 => w2.Create_Time == s.Max(max => max.Create_Time)).First() })
		.Select(s => new { s.Datas.No,s.Datas.Name,s.Key.City, s.Key.Town,s.Datas.Create_Time});
}

class Test
{
	public string No { set; get; }
	public string Name { set; get; }
	public string City { set; get; }
	public string Town { set; get; }
	public DateTime Create_Time { set; get; }
}
w4560000 iT邦研究生 5 級 ‧ 2018-11-25 19:10:48 檢舉

測試資料 這點我沒有想到,下次會記得提供 抱歉!
程式可以跑,非常感謝!! 又學到一招/images/emoticon/emoticon41.gif

暐翰 iT邦大師 1 級 ‧ 2018-11-25 21:48:59 檢舉

/images/emoticon/emoticon12.gif

我要發表回答

立即登入回答