要使用LINQ创建嵌套的group-by字典,您可以使用以下步骤:
以下是一个示例,说明如何使用LINQ创建嵌套的group-by字典:
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)。最后,我们将结果转换为嵌套的字典,其中外层字典的键是城市名称,内层字典的键是年龄。输出结果显示了每个城市中每个年龄段的学生及其成绩。
领取专属 10元无门槛券
手把手带您无忧上云