📅  最后修改于: 2023-12-03 15:10:08.306000             🧑  作者: Mango
在 C# 中,使用 Linq 可以轻松地将数据按照一个或多个列进行分组。本文将介绍如何使用 Linq 在 C# 中实现按多列分组。
假设我们有以下 Student 类型的对象:
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public string Major { get; set; }
}
我们想要按照年龄和专业分组,可以使用以下 Linq 查询:
var students = new List<Student>
{
new Student { Name = "Alice", Age = 20, Gender = "Female", Major = "Computer Science" },
new Student { Name = "Bob", Age = 21, Gender = "Male", Major = "Computer Science" },
new Student { Name = "Charlie", Age = 20, Gender = "Male", Major = "Mathematics" },
new Student { Name = "David", Age = 22, Gender = "Male", Major = "Mathematics" },
new Student { Name = "Emily", Age = 21, Gender = "Female", Major = "Computer Science" }
};
var groupedStudents = from student in students
group student by new { student.Age, student.Major };
这将返回一个 IGrouping
对象的集合,每个 IGrouping
对象对应一个分组:
foreach (var group in groupedStudents)
{
Console.WriteLine($"Age: {group.Key.Age}, Major: {group.Key.Major}");
foreach (var student in group)
{
Console.WriteLine($" {student.Name} ({student.Gender})");
}
}
输出结果为:
Age: 20, Major: Computer Science
Alice (Female)
Bob (Male)
Age: 20, Major: Mathematics
Charlie (Male)
Age: 21, Major: Computer Science
Emily (Female)
Age: 22, Major: Mathematics
David (Male)
可以看到,我们成功地按照年龄和专业将学生分组。
有时,我们需要使用自定义的函数来分组。例如,我们想要将字符串按照首字母分组,可以使用以下 Linq 查询:
var strings = new List<string> { "apple", "banana", "cat", "dog", "elephant", "fox" };
var groupedStrings = from s in strings
group s by s[0] into g
orderby g.Key
select new { FirstLetter = g.Key, Words = g };
foreach (var group in groupedStrings)
{
Console.WriteLine($"Words starting with '{group.FirstLetter}':");
foreach (var word in group.Words)
{
Console.WriteLine($" {word}");
}
}
这将返回一个匿名类型的对象的集合:
Words starting with 'a':
apple
Words starting with 'b':
banana
Words starting with 'c':
cat
Words starting with 'd':
dog
Words starting with 'e':
elephant
Words starting with 'f':
fox
在 C# 中,使用 Linq 可以轻松地按照一个或多个列进行分组。我们可以使用简单的语法来分组,也可以使用自定义的函数来分组。这些功能使得我们可以更方便地对数据进行处理和分析。