如何在Linq GroupBy中选择前N行

时间:2011-04-24 10:10:03

标签: c# linq

希望你能在这里帮助我。 我有一个预订列表,我想在每组TourOperators中获得前两行。

这是一个数据样本:

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

感谢。

2 个答案:

答案 0 :(得分:19)

First()替换为Take(2)并使用SelectMany()

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

更新:第一次忘记SelectMany。您希望展平结果(SelectMany执行此操作),否则您会得到IEnumerables的列表。

答案 1 :(得分:1)

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

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