Jonathan
Jonathan

Reputation: 15395

Using Linq to GroupBy and Select

I'm looking to do a GroupBy and a Select in Linq, but the following doesn't compile:

foreach (string fooName in fooList.GroupBy(f => f.Name).Select(f => f.Name))
{
    ...
}

Why am I unable to use f => f.name in my Select clause? More importantly, is there any way around this?

Upvotes: 1

Views: 292

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292355

GroupBy returns a sequence of IGrouping<TKey, TSource>, so the lambda parameter in the Select method is of type IGrouping<TKey, TSource>, not TSource. Instead you can do this:

foreach (string fooName in fooList.GroupBy(f => f.Name).Select(grouping => grouping.Key))
{
    ...
}

But anyway, there is a simpler way to achieve the same result:

foreach (string fooName in fooList.Select(f => f.Name).Distinct())
{
    ...
}

Upvotes: 5

Matt Greer
Matt Greer

Reputation: 62027

GroupBy groups the values into key value pairs, so you probably want

 foreach (string fooName in fooList.GroupBy(f => f.Name).Select(f => f.Key))
 {
    ...
 }

Upvotes: 1

Related Questions