温馨提示×

如何在C#中对Map集合进行分组统计

c#
小樊
83
2024-09-04 15:57:36
栏目: 编程语言

在C#中,你可以使用LINQ(Language Integrated Query)来对Map集合(在C#中通常表示为字典,Dictionary)进行分组统计

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        // 创建一个字典,表示Map集合
        Dictionary<string, int> map = new Dictionary<string, int>
        {
            {"A", 1},
            {"B", 2},
            {"A", 3},
            {"C", 4},
            {"B", 5},
            {"A", 6},
            {"C", 7}
        };

        // 使用LINQ对字典进行分组统计
        var groupedStats = from entry in map
                           group entry by entry.Key into g
                           select new
                           {
                               Key = g.Key,
                               Count = g.Count(),
                               Sum = g.Sum(x => x.Value)
                           };

        // 输出分组统计结果
        Console.WriteLine("Key | Count | Sum");
        foreach (var group in groupedStats)
        {
            Console.WriteLine($"{group.Key} | {group.Count} | {group.Sum}");
        }
    }
}

这个示例首先创建了一个包含重复键的字典。然后,我们使用LINQ查询对字典进行分组统计,按照键进行分组,并计算每个分组的元素数量和值的总和。最后,我们将分组统计结果输出到控制台。

注意:在这个示例中,我们使用了一个简单的字典,其中键是字符串类型,值是整数类型。你可以根据需要修改代码以适应你的实际情况。

0