c# - 使用 LINQ 删除字典中的重复项和这些重复项的计数

标签 c# linq

我有一些代码可以返回字典中的唯一元素,但我也想返回重复元素的计数。基本上将 dictionary[key, uniqueelement] 更改为 dictionary[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());

最佳答案

基于你已有的

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

关于c# - 使用 LINQ 删除字典中的重复项和这些重复项的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2940992/

相关文章:

c# - 在 C#.NET 中实现不固定多维数组的最佳方法是什么?

c# - 单元测试代码事件工作流

c# - 在多个应用程序(旨在同时访问一个数据库)之间共享一个 Entity Framework 4 数据模型的最佳方式是什么?

c# - 从函数返回 var

c# - For-Loop 和 LINQ 的延迟执行不能一起玩

c# - 如何使用事件处理程序将数据从一种形式传输到另一种形式

c# - 检查参数是否具有值的 MVC 操作属性?

c# - List<int> 上的 AllConsecutives

c# - 为什么 Enumerable.Single() 迭代所有元素,即使已经找到多个元素?

c# - 获取嵌套集合包含另一个集合中的项目的项目