开发者

How to select top N rows in a Linq GroupBy

开发者 https://www.devze.com 2023-02-28 03:38 出处:网络
hope you can help me out here. I have a list of Bookings where I would like to get the top 2 rows in each group of TourOperators.

hope you can help me out here. I have a list of Bookings where I would like to get the top 2 rows in each group of TourOperators.

here's a sample of the data:

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开发者_StackOverflow), 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" });

I have this Linq, but it only gives me the first Booking in each group:

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

The data I was hoping for was something like this:

31111111, 2011-05-01, SPI

32222222, 2011-05-02, SPI

11111111, 2011-05-01, VIN

12222222, 2011-05-02, VIN

Thanks.


Replace First() with Take(2) and use SelectMany():

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

Update: Forgot the SelectMany the first time. You want to flatten the result (which SelectMany does), otherwise you get a list of IEnumerables.


Try to use var and replace First() with Take(2):

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

精彩评论

暂无评论...
验证码 换一张
取 消