在C#中,Linq是一种用于查询和操作数据的强大工具。Linq中的Group By操作可以让你根据多个列对数据进行分组。以下是关于C# Linq Group By多列的详细解释。
概念:Linq中的Group By操作可以让你根据多个列对数据进行分组,以便对数据进行聚合操作。
优势:
应用场景:
推荐的腾讯云相关产品:
产品介绍链接地址:
以下是一个使用Linq Group By多列的示例:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
List<Student> students = new List<Student>
{
new Student { Name = "张三", Age = 21, Gender = "男", Score = 80 },
new Student { Name = "李四", Age = 22, Gender = "男", Score = 90 },
new Student { Name = "王五", Age = 21, Gender = "女", Score = 85 },
new Student { Name = "赵六", Age = 23, Gender = "女", Score = 95 },
new Student { Name = "钱七", Age = 22, Gender = "男", Score = 75 }
};
var groupedStudents = from student in students
group student by new { student.Age, student.Gender } into g
select new
{
g.Key.Age,
g.Key.Gender,
Count = g.Count(),
AverageScore = g.Average(s => s.Score)
};
foreach (var student in groupedStudents)
{
Console.WriteLine($"Age: {student.Age}, Gender: {student.Gender}, Count: {student.Count}, AverageScore: {student.AverageScore}");
}
}
}
class Student
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
public int Score { get; set; }
}
在这个示例中,我们使用Linq Group By多列操作按照年龄和性别对学生进行分组,并计算每个组的学生数量和平均分数。
领取专属 10元无门槛券
手把手带您无忧上云