使用 linq 在 IGrouping 中查找重复项

Finding duplicates in IGrouping Using linq

我想知道同一个人玩过的其他游戏数。例如,丽莎参加了第 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();
        }
    }
}