Search code examples
c#linqduplicatesigrouping

Finding duplicates in IGrouping Using linq


I would like to get the other number of games the same person has played in on. For example lisa plays in game 7 which is 1 other game. Tim and Josh both play in game 2 but also play in 3 other games. Is there a way through Igrouping to compare groups and see if the values are the same?

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

Solution

  • You cannot use the current lookup to get the information that you want. You need to query the list again to get the number of games for each person. Here is an exmaple:

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