gpt4 book ai didi

c# - 使用 linq 在 IGrouping 中查找重复项

转载 作者:行者123 更新时间:2023-11-30 17:37:42 25 4
gpt4 key购买 nike

我想获得同一个人参加过的其他比赛次数。例如,丽莎参加了第 7 场比赛,这是另外一场比赛。 Tim 和 Josh 都参加了第 2 场比赛,但也参加了另外 3 场比赛。有没有办法通过 Igrouping 来比较组,看看值是否相同?

public List<Game> DummyDataSet()
{
dataSet.Add(new Game { GameNo = 1, FirstName = "Lisa" });
dataSet.Add(new Game { GameNo= 2, FirstName = "Tim" });
dataSet.Add(new Game { GameNo = 2, FirstName = "Josh" });
dataSet.Add(new Game { GameNo = 3, FirstName = "Susan" });
dataSet.Add(new Gamee { GameNo = 4, FirstName = "Tim" });
dataSet.Add(new Gamee { GameNo = 5, FirstName = "Tim" });
dataSet.Add(new Gamee { GameNo = 5, FirstName = "Josh" });
dataSet.Add(new Game { GameNo = 6, FirstName = "Josh" });
dataSet.Add(new Game { GameNo = 7, FirstName = "Lisa" });

return dataSet;
}

public void numOfOtherMissions()
{
List<Game> something;
something = DummyDataSet();
var grouped = something.ToLookup(x => x.GameNo, x => x.FirstName);
foreach (IGrouping<int, string> item in grouped)
{
Console.Write(item.Key);
Console.Write(": ");
var result = grouped.ToLookup(z => FirstName);
foreach (var value in item)
{
int games = 0;
if(result == item)
{
othergames++;
}
else
{
othergames = 0;
}
Console.Write(value + " " + othergames);
Console.WriteLine();
}
}
}

最佳答案

您不能使用当前查找来获取所需的信息。您需要再次查询列表以获取每个人的游戏数量。这是一个例子:

public void numOfOtherMissions(List<Game> something)
{
var grouped = something.ToLookup(x => x.GameNo, x => x.FirstName);

//Create a dictionary that holds the number of games for each person
var gamesForPerson =
something
.GroupBy(x => x.FirstName)
.ToDictionary(x => x.Key, x => x.Count());

foreach (IGrouping<int, string> item in grouped)
{
Console.Write(item.Key);
Console.Write(": ");

foreach (var value in item)
{
//Get total number of games for this person and subtract 1
var othergames = gamesForPerson[value] - 1;

Console.Write(value + " " + othergames);
Console.WriteLine();
}
}
}

关于c# - 使用 linq 在 IGrouping 中查找重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37645341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com