c# – 如何在Linq GroupBy中选择前N行

前端之家收集整理的这篇文章主要介绍了c# – 如何在Linq GroupBy中选择前N行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
希望你能帮助我在这里.
我有一个预订列表,我希望在每组TourOperators中获得前2排.

以下是数据示例:

List<Booking> list = new List<Booking>();
        list.Add(new Booking() { BookingNo = "31111111",DepDate = new DateTime(2011,5,1),TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "32222222",2),TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "33333333",3),TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "34444444",4),TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "35555555",5),TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "36666666",6),TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "11111111",TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "12222222",TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "13333333",TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "14444444",TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "15555555",TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "16666666",TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "17777777",7),TourOperator = "VIN" });

我有这个Linq,但它只给我在每个组的第一个预订:

List<Booking> yetAnotherList = list.GroupBy(row => row.TourOperator)
            .Select(g => g.OrderBy(row => row.DepDate).First()).ToList();

我所希望的数据是这样的:

31111111,2011-05-01,SPI
32222222,2011-05-02,SPI
11111111,VIN
12222222,VIN

谢谢.

解决方法

用Take(2)替换First()并使用SelectMany():
List<Booking> yetAnotherList = 
                 list.GroupBy(row => row.TourOperator)
                     .SelectMany(g => g.OrderBy(row => row.DepDate).Take(2)) 
                     .ToList();

更新:第一次忘记选择你想平坦化结果(SelectMany做的),否则你得到一个IEnumerables列表.

猜你在找的C#相关文章