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列表.

相关文章

在项目中使用SharpZipLib压缩文件夹的时候,遇到如果目录较深,则压缩包中的文件夹同样比较深的问题。比...
项目需要,几十万张照片需要计算出每个照片的特征值(调用C++编写的DLL)。 业务流程:选择照片...
var array = new byte[4]; var i = Encoding.UTF8.GetBytes(100.ToString(&quot;x2&quot;));//...
其实很简单,因为Combox的Item是一个K/V的object,那么就可以把它的items转换成IEnumerable&lt;Dic...
把.net4.6安装包打包进安装程序。 关键脚本如下: 头部引用字符串对比库 !include &quot;WordFunc....
项目需求(Winform)可以批量打印某个模板,经过百度和摸索,使用iTextSharp+ZXing.NetʿreeSp...