Using LINQ to remove duplicates in dictionary and the count of those duplicates

I have some code that returns unique elements in my dictionary, but I would also like to return the count of the duplicate elements. Basically change dictionary[key, uniqueelement] to dictionary[uniqueelement, count]. Here is my code that just returns the unique elements.

var uniqueItems = deviceInstances.Children.GroupBy(pair => pair.Value.Information.UnderlyingDeviceType)
                  .Select(group => group.First())
                  .ToDictionary(pair => pair.Key, pair => pair.Value.Information.UnderlyingDeviceType.ToString());


Based upon what you already have

var uniqueItems = deviceInstances.Children.GroupBy(pair => pair.Value.Information.UnderlyingDeviceType) 
                  .Select(group => new { Pair = group.First(), Count = group.Count() }) 
                  .ToDictionary(g => g.Pair.Value.Information.UnderlyingDeviceType.ToString(), g => g.Count); 

Based on this demo

Dictionary<int, string> dictionary = new Dictionary<int, string>();
dictionary.Add(1, "Alpha");
dictionary.Add(2, "Bravo");
dictionary.Add(3, "Charlie");
dictionary.Add(4, "Alpha");
dictionary.Add(5, "Bravo");
dictionary.Add(6, "Alpha");

var uniqueItems = dictionary
    .GroupBy(kvp => kvp.Value)
    .Select(g => new { g.Key, Count = g.Count() })
    .ToDictionary(g => g.Key, g => g.Count);

foreach (var kvp in uniqueItems)
    Console.WriteLine("{0}\t{1}", kvp.Key, kvp.Value);

Dictionary<T, U> source = GetDictionary();

List<IGrouping<U, T> valueGroupList = source
  .GroupBy(kvp => kvp.Value, kvp => kvp.Key)

Dictionary<T, U> withoutDupes = valueGroupList
  .Where(g => !g.Skip(1).Any())
  .ToDictionary(g => g.First(), g.Key);

Dictionary<U, int> dupesWithCount = valueGroupList
  .Where(g => g.Skip(1).Any())
  .ToDictionary(g.Key, g.Count())

Need Your Help

Get the relation type between two Facebook friends

facebook facebook-graph-api facebook-fql

I'm building a "Clue" like kind of game where you have to find which friend of yours is the criminal with some clues to help you.