如何在Linq GroupBy中选择前N行

  • 本文关键字:选择 GroupBy Linq c# linq
  • 更新时间 :
  • 英文 :


希望你能帮我解决这个问题。我有一个预订列表,我想在每组touoperator中获得前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", DepDate = new DateTime(2011, 5, 2), TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "33333333", DepDate = new DateTime(2011, 5, 3), TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "34444444", DepDate = new DateTime(2011, 5, 4), TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "35555555", DepDate = new DateTime(2011, 5, 5), TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "36666666", DepDate = new DateTime(2011, 5, 6), TourOperator = "SPI" });
        list.Add(new Booking() { BookingNo = "11111111", DepDate = new DateTime(2011, 5, 1), TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "12222222", DepDate = new DateTime(2011, 5, 2), TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "13333333", DepDate = new DateTime(2011, 5, 3), TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "14444444", DepDate = new DateTime(2011, 5, 4), TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "15555555", DepDate = new DateTime(2011, 5, 5), TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "16666666", DepDate = new DateTime(2011, 5, 6), TourOperator = "VIN" });
        list.Add(new Booking() { BookingNo = "17777777", DepDate = new DateTime(2011, 5, 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, 2011-05-01, VIN
12222222, 2011-05-02, VIN

谢谢。

First()替换为Take(2),使用SelectMany():

List<Booking> yetAnotherList = 
                 list.GroupBy(row => row.TourOperator)
                     .SelectMany(g => g.OrderBy(row => row.DepDate).Take(2)) 
                     .ToList();

Update:第一次忘记SelectMany。您希望将结果平整化(SelectMany就是这样做的),否则您将得到IEnumerables的列表。

尝试使用var并将First()替换为Take(2):

var yetAnotherList = list.GroupBy(row => row.TourOperator)
                  .Select(g => g.OrderBy(row => row.DepDate).Take(2)).ToList(); 

相关内容

  • 没有找到相关文章

最新更新