首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使用LINQ创建嵌套的group-by字典?

要使用LINQ创建嵌套的group-by字典,您可以使用以下步骤:

  1. 首先,确保您已经引用了System.Linq命名空间。
  2. 创建一个数据集合,例如一个List<T>,其中T是一个包含要分组的属性的类。
  3. 使用GroupBy方法对数据集合进行分组。
  4. 对每个分组进行嵌套分组。
  5. 将结果转换为字典。

以下是一个示例,说明如何使用LINQ创建嵌套的group-by字典:

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        // 创建一个数据集合
        List<Student> students = new List<Student>
        {
            new Student { Name = "Alice", Age = 25, City = "New York", Score = 90 },
            new Student { Name = "Bob", Age = 23, City = "New York", Score = 85 },
            new Student { Name = "Charlie", Age = 26, City = "Los Angeles", Score = 92 },
            new Student { Name = "David", Age = 24, City = "Los Angeles", Score = 88 },
            new Student { Name = "Eva", Age = 25, City = "San Francisco", Score = 91 },
            new Student { Name = "Frank", Age = 23, City = "San Francisco", Score = 87 }
        };

        // 使用LINQ创建嵌套的group-by字典
        var nestedGroupedDict = students
            .GroupBy(s => s.City)
            .ToDictionary(g => g.Key, g => g
                .GroupBy(s => s.Age)
                .ToDictionary(sg => sg.Key, sg => sg.ToList()));

        // 输出结果
        foreach (var cityGroup in nestedGroupedDict)
        {
            Console.WriteLine($"City: {cityGroup.Key}");
            foreach (var ageGroup in cityGroup.Value)
            {
                Console.WriteLine($"  Age: {ageGroup.Key}");
                foreach (var student in ageGroup.Value)
                {
                    Console.WriteLine($"    Name: {student.Name}, Score: {student.Score}");
                }
            }
        }
    }
}

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
    public int Score { get; set; }
}

在这个示例中,我们首先创建了一个Student类的List<T>数据集合。然后,我们使用LINQ对数据集合进行分组,首先按城市(City),然后按年龄(Age)。最后,我们将结果转换为嵌套的字典,其中外层字典的键是城市名称,内层字典的键是年龄。输出结果显示了每个城市中每个年龄段的学生及其成绩。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券