1

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?

2 Answers 2

5

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()) { ... } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer and the thorough explanation.
1

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)) { ... } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.