Linq 过滤器以避免循环

Linq filter to avoid a loop

我正在尝试制定 LINQ 查询,但不是专家,所以无论我尝试什么都行不通。我想过滤列表以从下面的列表中获取电子邮件 ID,其中分数为 0 按团队名称分组。

我尝试这样做的方式是:

  1. 获取不同团队名称的列表。
  2. 遍历每个不同的团队名称并获取分数为 0 的电子邮件 ID。
Team    Name   Score    EmailId  
Hawk    Amy     0       Amy@gmail.com  
Hawk    Aby     0       Aby@gmail.com  
Hawk    Raf     1       Raf@gmail.com  
Hawk    Jay     2       Jay@gmail.com  
Eagle   Blu     0       Blu@gmail.com  
Eagle   Tru     1       Tru@gmail.com  

我想得到两行:HawkAmy@gmail.com, Aby@gmail.com,下一个结果将是 EagleBlue@gmail.com是否可以通过 LINQ 一步完成?

不确定您目前在做什么,但我会这样做

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

Want to filter the list to get email-ids where score is 0 grouped by the Team Name.

筛选列表以获得 email-ids 其中分数为 0

var filteredList = list.Where(record => records.Score == 0);

按团队名称分组

var groupedByTeamName = filteredList.GroupBy(record => record.Team)

如果我没记错的话,这将是 return 和 IEnumerable<IGrouping<TRecord, TTeam>>IGrouping<T,K> 只是一个包含 Key 属性 的列表,其中包含您分组的内容(在本例中为团队)。

你当然可以在 cascade-style:

中调用它们
list.Where(record => records.Score == 0).GroupBy(record => record.Team);

但调试会有点困难,因为您将不得不 select 代码并快速观看句子的部分内容。有时这是行不通的。

Want to filter the list to get email-ids where score is 0 grouped by the Team Name.

这么说难吗:

I want all emails of team-members that are in teams that didn't score?

将您的数据分组到"Teams with their players and their scores";只保留那些只有零分的球队并提取球员的电子邮件。

为此我们使用 overload of GroupBy with aKeySelector and aResultSelector

var emailsOfPlayersInTeamsWithZeroScor = myInput.GroupBy

    // keySelector: the team
    .GroupBy(inputItem => inputItem.Team,

    // ResultSelector: from every Team with its players and scores
    // make sequences of emails of players and check if there is a score at all
    (team, players) => new
    {
        // not interested in the team

        // remember if all scores are zero
        HasOnlyZeroScore = players.All(player.Score == 0),

        // remember all emails of the players in the team
        PlayerEmails = players.Select(player => player.Email),
    })

    // keep only the items with a zero score
    .Where(team => team.HasOnlyZeroScore)

    // and select the lists of emails per team as one big list:
    .SelectMany(team => team.PlayerEmails);

简单的comme bonjour!