简体   繁体   English

使用字典C#的Linq查询

[英]Linq Query with Dictionary C#

I have a dictionary of teams that have a win percentage. 我有一本关于获胜百分比的球队的字典。 I want to be able to get back a dictionary with the teams that I find have the same win percentage as another team. 我希望能够找到与其他团队具有相同获胜率的团队一起获得字典。 Before I was doing this: 在我这样做之前:

<!-- language: lang-js -->

foreach (var r in divRanks)
{
    foreach (var rec in divRanks)
    {
        if (r.teamID != rec.teamID)
        {
            if (r.winPct == rec.winPct)
            {
                r.tied = true;
                rec.tied = true;
            }
        }
    }
}

I feel there must be a better way for me to use LINQ to query for the teams and then set my tied variable that way. 我觉得必须有一种更好的方法来使用LINQ来查询团队,然后以这种方式设置我的绑定变量。 I need theses results after including the records that weren't tied so I can work with them. 在包括未捆绑的记录之后,我需要这些结果,以便我可以使用它们。

You can group by on winPct , filter out the groups with only one member, and set tied to true on all other items. 您可以通过组winPct ,筛选出各组只有一个成员,并且集tiedtrue上的所有其他项目。

This LINQ query is using the same divRanks as your nested foreach loops: 此LINQ查询使用的嵌套divRanks与嵌套的foreach循环相同:

var tied = divRanks
    // Make groups by winning percentage
    .GroupBy(r => r.winPct)
    // Throw away all groups of one
    .Where(g => g.Count() > 1)
    // Flatten the groups
    .SelectMany(g => g);
// Go through the ties, and set the flag
foreach (var t in tied) {
    t.tied = true;
} 

you should use GroupBy in combination with ToDictionary: 您应该结合使用GroupBy和ToDictionary:

var dict = list.GroupBy(item => item.WinPct).ToDictionary(group => group.Key);
foreach (var item in dict)
{
    Console.Out.WriteLine("Key (winpct which is same for items): {0}", item.Key);
    if(item.Value.Count() > 1)
    {
        foreach (var groupItem in item.Value)
        {
            Console.Out.WriteLine("GroupItem: {0} - {1}", groupItem.TeamId, groupItem.WinPct);
            item.Tied = true;
        }
    }
}

input: 输入:

list.Add(new Rank() { TeamId = 1, WinPct = 1 });
list.Add(new Rank() { TeamId = 2, WinPct = 1 });
list.Add(new Rank() { TeamId = 3, WinPct = 2 });
list.Add(new Rank() { TeamId = 4, WinPct = 2 });
list.Add(new Rank() { TeamId = 5, WinPct = 5 });
list.Add(new Rank() { TeamId = 6, WinPct = 6 });

output: 输出:

Key (winpct which is same for items): 1
GroupItem: 1 - 1
GroupItem: 2 - 1
Key (winpct which is same for items): 2
GroupItem: 3 - 2
GroupItem: 4 - 2
Key (winpct which is same for items): 5
GroupItem: 5 - 5
Key (winpct which is same for items): 6
GroupItem: 6 - 6

EDIT: now it will also set the tied property. 编辑:现在它还将设置绑定属性。 I thought you just make this hack to merge then somehow after into a dictionary. 我以为您只是将这种技巧合并,然后合并成字典。 if you just want to set the tied property you better go with dasblinkenlights solution. 如果只想设置tied属性,最好使用dasblinkenlights解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM