'LINQ expression: Specifing maximum groupby size

Is there a elegant way of doing following in LINQ or should I write an extension for this

i have a list of objects that need to be grouped by startdate

lets say

09.00, 13.00, 13.00, 13.00, 15.00,

var groupedStartDates = startdate.groupby(x => x.StartDate);

I need to have maximum size of group to be 2.

Expected result is

var groupedStartDates = startDate.GroupBy(x => x.StartDate);
List
    list1 {09.00}
    list2 {13.00; 13.00}
    list3 {13.00}
    list4 {15.00}


Solution 1:[1]

If I understand your question correctly, you can use Take:

var result= startDate.GroupBy(x => x.StartDate)
                     .Select(x => x.Take(2))
                     .ToList();

Each group will contains at most 2 members and additional items of groups will not return.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1