我正在尝试使用LINQ从列表中获取最旧的记录。我只是想要 TOP 记录。看起来FirstOrDefault
方法可以解决问题,但在LINQPad中测试我的查询。我得到的数据集不仅仅是一条记录..
任何人都知道如何返回 1条记录?
List<Event> schedule = new List<Event>()
{
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();
答案 0 :(得分: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在评论中所建议的那样,在分组之前订购你的元素。
答案 1 :(得分:1)
只是为了解释已经发布的答案的原因。
OrderByDescending返回一个IOrderedEnumerable,并且您在该返回值上调用FirstOrDefault()方法。 将查询包含在“()”中,如同声明的octavioccl的答案一样,将在查询结果上调用FirstOrDefault()方法。