Search code examples
c#asp.netlistlinqlinq-to-objects

Linq filter to avoid a loop


I am trying to formulate a LINQ query but not a pro at it so whatever I try is not working. I would like to filter the list to get email-ids from below list where score is 0 grouped by the Team Name.

The way I was trying to do it was:

  1. Get list of distinct Team Names.
  2. Loop through each distinct team name and get the email-ids where score is 0.
Team    Name   Score    EmailId  
Hawk    Amy     0       [email protected]  
Hawk    Aby     0       [email protected]  
Hawk    Raf     1       [email protected]  
Hawk    Jay     2       [email protected]  
Eagle   Blu     0       [email protected]  
Eagle   Tru     1       [email protected]  

I would like to get two lines: Hawk and [email protected], [email protected] and the next result would be Eagle with [email protected]. Is this possible through LINQ and in a single step?


Solution

  • Not sure what you're currently doing, but this is how I would do it

    var result = list.Where(p => p.Score == 0)
                     .Select(p => new{p.Team, p.EmailId})
                     .GroupBy(p => p.Team)
                     .Distinct();