How to select top N rows in a Linq GroupBy

前端 未结 2 718
借酒劲吻你
借酒劲吻你 2021-02-19 08:39

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:

相关标签:
2条回答
  • 2021-02-19 08:57

    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.

    0 讨论(0)
  • 2021-02-19 08:57

    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 讨论(0)
提交回复
热议问题