我正在尝试使用LINQ从列表中获取最旧的记录.我只想要TOP记录.看起来FirstOrDefault
方法可以解决问题,但在LINQPad中测试我的查询.我得到的数据集不仅仅是一条记录..
有谁知道如何返回1条记录?
Listschedule = new List () { new Event(){eventID = 776734, eventName = "HGP", eventStartDate = Convert.ToDateTime("2011-09-01"), eventEndDate = Convert.ToDateTime("2011-09-18"), runningHours = 0.0000, runningStartStops = 0.0000}, new Event(){eventID = 776735, eventName = "CI", eventStartDate = Convert.ToDateTime("2012-10-01"), eventEndDate = Convert.ToDateTime("2012-10-11"), runningHours = 0.0000, runningStartStops = 0.0000}, new Event(){eventID = 776736, eventName = "HGP", eventStartDate = Convert.ToDateTime("2014-03-01"), eventEndDate = Convert.ToDateTime("2014-03-18"), runningHours = 0.0000, runningStartStops = 0.0000}, new Event(){eventID = 779236, eventName = "CI", eventStartDate = Convert.ToDateTime("2015-11-10"), eventEndDate = Convert.ToDateTime("2015-11-23"), runningHours = 2774.3300, runningStartStops = 111.3400}, new Event(){eventID = 779364, eventName = "MA", eventStartDate = Convert.ToDateTime("2017-03-11"), eventEndDate = Convert.ToDateTime("2017-04-04"), runningHours = 4176.0200, runningStartStops = 104.3400}, new Event(){eventID = 779365, eventName = "CI", eventStartDate = Convert.ToDateTime("2019-04-05"), eventEndDate = Convert.ToDateTime("2019-04-13"), runningHours = 8054.6700, runningStartStops = 232.5100}, new Event(){eventID = 779366, eventName = "HGP", eventStartDate = Convert.ToDateTime("2021-04-02"), eventEndDate = Convert.ToDateTime("2021-04-19"), runningHours = 13473.1300, runningStartStops = 389.3500}, new Event(){eventID = 779367, eventName = "CI", eventStartDate = Convert.ToDateTime("2023-03-31"), eventEndDate = Convert.ToDateTime("2023-04-08"), runningHours = 18930.8900, runningStartStops = 520.0200} }; var q = from evt in schedule where "MA,HGP".Contains(evt.eventName) group evt by evt.eventID into x select x.OrderByDescending(t => t.eventStartDate).FirstOrDefault(); //LINQPad method to show results q.Dump();
octavioccl.. 6
您需要在括号中关闭查询:
var q = (from evt in schedule where "MA,HGP".Contains(evt.eventName) group evt by evt.eventID into x select x.OrderByDescending(t => t.eventStartDate)).FirstOrDefault();
您的查询是选择每个已排序组的第一个元素.
但是,如果您正在寻找最新的活动,为什么还需要分组呢?尝试将其更改group by
为order by
:
var q = (from evt in schedule where "MA,HGP".Contains(evt.eventName) order evt by evt.eventStartDate select x).FirstOrDefault();
或者,正如@TimSchmelter在评论中所建议的那样,在对元素进行分组之前对其进行排序.
您需要在括号中关闭查询:
var q = (from evt in schedule where "MA,HGP".Contains(evt.eventName) group evt by evt.eventID into x select x.OrderByDescending(t => t.eventStartDate)).FirstOrDefault();
您的查询是选择每个已排序组的第一个元素.
但是,如果您正在寻找最新的活动,为什么还需要分组呢?尝试将其更改group by
为order by
:
var q = (from evt in schedule where "MA,HGP".Contains(evt.eventName) order evt by evt.eventStartDate select x).FirstOrDefault();
或者,正如@TimSchmelter在评论中所建议的那样,在对元素进行分组之前对其进行排序.