使用LINQ删除字典中的重复项以及这些重复项的计数

时间:2010-05-31 01:37:42

标签: c# linq

我有一些代码在我的字典中返回唯一元素,但我还想返回重复元素的计数。基本上将字典[key,uniqueelement]更改为字典[uniqueelement,count]。这是我的代码,只返回唯一元素。

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

2 个答案:

答案 0 :(得分:6)

基于你已经拥有的东西

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

基于此演示

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

答案 1 :(得分:0)

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

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

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