Reputation: 15395
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
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
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