1. LINQ简介
LINQ(Language Integrated Query)是C#中的一种查询语言,允许你以声明性的方式来操作数据。LINQ将查询功能直接集成到C#语言中,使得数据查询更加简洁和强大。LINQ可以用于多种数据源,如对象、XML、数据库等。
- 基本结构
var query = from element in collection where condition select element;
2. 基本查询操作
基本查询操作包括where
、select
、orderby
等子句。
-
简单查询
int[] numbers = { 2, 3, 4, 5 }; var result = from n in numbers where n > 3 select n; foreach (var number in result) { Console.WriteLine(number); }
-
排序查询
string[] names = { "Alice", "Bob", "Charlie" }; var sortedNames = from name in names orderby name select name; foreach (var name in sortedNames) { Console.WriteLine(name); }
-
复杂查询
var complexQuery = from n in numbers where n % 2 == 0 orderby n descending select n; foreach (var number in complexQuery) { Console.WriteLine(number); }
3. Lambda表达式
Lambda表达式是一种匿名函数,可以包含表达式和语句,并且可以用于创建委托或表达式树类型。LINQ中经常使用Lambda表达式。
-
基本语法
(parameters) => expression
-
示例
Func<int, int> square = x => x * x; Console.WriteLine(square(5)); // 输出 25 int[] numbers = { 2, 3, 4, 5 }; var result = numbers.Where(n => n > 3).Select(n => n * 2); foreach (var number in result) { Console.WriteLine(number); // 输出 8, 10 }
4. LINQ to Objects, LINQ to XML, LINQ to SQL
-
LINQ to Objects
LINQ to Objects用于在内存中的对象集合上执行查询操作。string[] names = { "Alice", "Bob", "Charlie" }; var result = names.Where(name => name.Contains('a')); foreach (var name in result) { Console.WriteLine(name); // 输出 Alice, Charlie }
-
LINQ to XML
LINQ to XML允许你使用LINQ查询和操作XML数据。XElement xmlTree = new XElement("Root", new XElement("Child", "child content"), new XElement("Child", "more child content") ); var result = from el in xmlTree.Elements("Child") where el.Value.Contains("child") select el; foreach (var el in result) { Console.WriteLine(el); // 输出 <Child>child content</Child>, <Child>more child content</Child> }
-
LINQ to SQL
LINQ to SQL允许你使用LINQ查询SQL数据库。using (var context = new MyDataContext()) { var result = from user in context.Users where user.Age > 18 select user; foreach (var user in result) { Console.WriteLine(user.Name); } }
总结
- LINQ简介:LINQ是一种查询语言,集成在C#中,支持对多种数据源的查询。
- 基本查询操作:包括
where
、select
、orderby
等子句,可以用于过滤、投影和排序数据。 - Lambda表达式:匿名函数,常用于LINQ查询中,使代码更加简洁。
- LINQ to Objects, LINQ to XML, LINQ to SQL:分别用于查询内存中的对象、XML数据和SQL数据库。