使用linq在IGrouping中查找重复项

时间:2016-06-05 18:27:06

标签: c# linq duplicates igrouping

我想获得同一个人玩过的其他数量的游戏。例如,lisa在游戏7中玩,这是另外一个游戏。 Tim和Josh都参加了第二场比赛,但也参加了其他三场比赛。有没有办法通过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();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

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

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();
        }
    }
}