INQ(Language Integrated Query)是C#中用于处理数据的强大工具。它使得对集合、数据库、XML等数据源的查询更加简洁和可读。
基础知识
LINQ的优点
- 统一语法:通过一致的语法处理不同的数据源。
- 延迟执行:查询在获取结果时才执行,减少不必要的计算。
- 类型安全:在编译时检查查询的正确性,减少运行时错误。
常用操作符
- 过滤:Where 用于过滤集合中的元素。
- 排序:OrderBy, OrderByDescending 用于对元素进行排序。
- 选择:Select 用于从集合中选择特定属性或值。
- 聚合:Sum, Count, Average, Max, Min用于对集合进行聚合计算。
- 连接:Join 用于连接两个集合。
LINQ 查询语法
方法语法
using System;
using System.Collections.Generic;
using System.Linq;
public class LINQExample
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 5, 10, 15, 20, 25 };
// 使用方法语法
var filteredNumbers = numbers.Where(n => n > 10).OrderBy(n => n);
foreach (var num in filteredNumbers)
{
Console.WriteLine(num); // 输出:15, 20, 25
}
}
}
查询表达式语法
using System;
using System.Collections.Generic;
using System.Linq;
public class LINQExample
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 5, 10, 15, 20, 25 };
// 使用查询表达式语法
var filteredNumbers = from n in numbers
where n > 10
orderby n
select n;
foreach (var num in filteredNumbers)
{
Console.WriteLine(num); // 输出:15, 20, 25
}
}
}
高级功能
分组
使用group by对元素分组。
List<string> words = new List<string> { "apple", "banana", "apricot", "cherry" };
var groupedWords = from word in words
group word by word[0] into g
select new { FirstLetter = g.Key, Words = g };
foreach (var item in groupedWords)
{
Console.WriteLine($"Words starting with {item.FirstLetter}: {string.Join(", ", item.Words)}");
}
联接(Join)
使用Join连接两个集合。
List<string> students = new List<string> { "Alice", "Bob", "Charlie" };
List<int> scores = new List<int> { 85, 90, 78 };
var studentScores = students.Zip(scores, (student, score) => new { Student = student, Score = score });
foreach (var entry in studentScores)
{
Console.WriteLine($"{entry.Student}: {entry.Score}");
}
实践习题
1.基本查询
给定一个整数列表,筛选出所有的偶数并按升序排列,然后输出这些数字。
using System;
using System.Collections.Generic;
using System.Linq;
public class EvenNumbersExample
{
public static void Main(string[] args)
{
List<int> numbers = new List<int> { 5, 10, 15, 20, 25, 30 };
// LINQ 查询:过滤偶数并排序
var evenNumbers = numbers.Where(n => n % 2 == 0).OrderBy(n => n);
Console.WriteLine("Even numbers:");
foreach (var num in evenNumbers)
{
Console.WriteLine(num); // 输出:10, 20, 30
}
}
}
- 使用Where方法过滤出偶数。
- 使用OrderBy对结果进行排序。
2.复杂查询
创建一个包含多个学生及其成绩的字典,查询出成绩高于80的学生名字,并按成绩降序排列。
using System;
using System.Collections.Generic;
using System.Linq;
public class StudentScoresExample
{
public static void Main(string[] args)
{
Dictionary<string, int> studentScores = new Dictionary<string, int>
{
{ "Alice", 85 },
{ "Bob", 90 },
{ "Charlie", 78 },
{ "David", 92 }
};
var topStudents = studentScores
.Where(s => s.Value > 80)
.OrderByDescending(s => s.Value)
.Select(s => s.Key);
Console.WriteLine("Top students:");
foreach (var student in topStudents)
{
Console.WriteLine(student); // 输出:David, Bob, Alice
}
}
}
- 使用Where方法过滤出成绩高于80的学生。
- 使用OrderByDescending对结果按成绩降序排序。
- 使用Select提取学生姓名。
3.分组与聚合
给定一组单词,将它们按首字母分组,并统计每组中单词的数量。
using System;
using System.Collections.Generic;
using System.Linq;
public class GroupWordsExample
{
public static void Main(string[] args)
{
List<string> words = new List<string> { "apple", "apricot", "banana", "cherry", "avocado", "blueberry" };
var groupedWords = from word in words
group word by word[0] into g
select new { FirstLetter = g.Key, Count = g.Count() };
Console.WriteLine("Grouped words by first letter:");
foreach (var group in groupedWords)
{
Console.WriteLine($"Letter: {group.FirstLetter}, Count: {group.Count}");
// 输出:
// Letter: a, Count: 3
// Letter: b, Count: 2
// Letter: c, Count: 1
}
}
}
- 使用group by将单词按首字母分组。
- 使用Count()计算每个组中的单词数量。
这些例子展示了如何利用LINQ来进行数据查询、排序、分组和聚合操作。如有其他问题或需要进一步讲解,请随时联系我!