下面是对“C#使用LINQ查询表达式的基本子句总结”的完整攻略:
C#使用LINQ查询表达式的基本子句总结
什么是LINQ
LINQ是Language-Integrated Query,即语言集成查询的缩写,是.NET框架中提供的一种用于统一访问各种类型数据的高级查询技术。
LINQ查询表达式的基本子句
在LINQ中,查询操作被分解成一些基本的表达式。以下是几个常见的表达式:
From子句
From子句用于指定查询的数据源,可以是数组、集合、数据表、或者其他的可迭代对象。
int[] numbers = { 1, 2, 3, 4 };
var query = from n in numbers
select n;
Where子句
Where子句用于筛选符合条件的数据。
int[] numbers = { 1, 2, 3, 4 };
var query = from n in numbers
where n % 2 == 0
select n;
OrderBy子句
OrderBy子句用于对查询结果进行排序。
string[] names = { "Mary", "Joe", "John", "Kate" };
var query = from n in names
orderby n.Length
select n;
Select子句
Select子句用于选择查询结果集的特定字段。
string[] names = { "Mary", "Joe", "John", "Kate" };
var query = from n in names
select n.ToUpper();
Group By子句
Group By子句用于根据指定键对结果集进行分组。
string[] names = { "Mary", "Joe", "John", "Kate" };
var query = from n in names
group n by n.Length into g
select new { Length = g.Key, Names = g };
Join子句
Join子句用于将两个数据源联接在一起,通过指定联接条件来组合结果集。
var employees = new[] {
new { Id = 1, Name = "Mary", DepartmentId = 1 },
new { Id = 2, Name = "Joe", DepartmentId = 2 },
new { Id = 3, Name = "John", DepartmentId = 1 }
};
var departments = new[] {
new { Id = 1, Name = "Sales" },
new { Id = 2, Name = "Finance" },
};
var query = from e in employees
join d in departments on e.DepartmentId equals d.Id
select new { e.Name, Department = d.Name };
示例
下面是两个示例,用于说明LINQ查询表达式基本子句的使用:
示例1
假设我们有一个字符串数组,我们要筛选出其中长度大于3的字符串,并对其进行排序和格式化输出。
string[] names = { "Mary", "Joe", "John", "Kate" };
var query = from n in names
where n.Length > 3
orderby n
select n.ToUpper();
foreach (var item in query)
{
Console.WriteLine(item);
}
输出结果为:
JOHN
KATE
MARY
示例2
假设我们有一个包含学生信息的列表和一个包含成绩的列表,我们要根据学生姓名和成绩进行联接,并计算每个学生的平均成绩。
var students = new[] {
new { Name = "Mary", Id = 1 },
new { Name = "Joe", Id = 2 },
new { Name = "John", Id = 3 },
};
var scores = new[] {
new { StudentId = 1, Score = 90 },
new { StudentId = 2, Score = 80 },
new { StudentId = 3, Score = 95 },
new { StudentId = 1, Score = 85 },
new { StudentId = 2, Score = 75 },
new { StudentId = 3, Score = 90 },
};
var query = from s in students
join sc in scores on s.Id equals sc.StudentId into g
select new { s.Name, Average = g.Average(x => x.Score) };
foreach (var item in query)
{
Console.WriteLine($"{item.Name}: {item.Average}");
}
输出结果为:
Mary: 87.5
Joe: 77.5
John: 92.5
至此,我们完成了对“C#使用LINQ查询表达式的基本子句总结”的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#使用LINQ查询表达式的基本子句总结 - Python技术站