Search code examples
c#linqduplicatesskiptake

LINQ: Skip and Take duplicates


I have an IQueryable containing items where everything is already grouped, so something like

var animals = new List<string>{"duck", "duck", "duck", "goose", "goose", "cow", "cow", "cow", "rabbit"}.AsQueryable();

If I do

animals.Skip(2).Take(2);

I would get "duck", "goose". However, I would like to skip the first two groups of distinct entries and get the third and fourth ("cow", "cow", "cow", "rabbit"). Is there a nice way of doing this in LINQ?


Solution

  • You can use grouping to easily skip the first ones, but it's a bit trickier to get the enumerated set out. I think this should do it:

    animals.GroupBy(a => a)
           .Skip(2)
           .Take(2)
           .SelectMany(a => a);
    

    The GroupBy and Skip let us handle these as groups, which gets the first bit of your requirement. Then we just re-expand the grouping with the SelectMany at the end.