简体   繁体   中英

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. 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.

This LINQ query is using the same divRanks as your nested foreach loops:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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