.Net Framework 4/C# LINQ*

一、什么是 LINQ

LINQ 是一种在 C# 等编程语言中集成的查询功能,它允许开发者使用编程语言本身的语法进行数据查询,而不是嵌入式的字符串 SQL 语句。LINQ 查询可以应用于对象、XML 和数据库等多种数据源。

二、LINQ 查询的基本构成

LINQ 查询通常包含以下几个部分:

  1. from 子句:指定查询操作的数据源和范围变量;
  2. select 子句:指定查询结果的形式。
  3. orderby 子句:对结果进行排序;
  4. where 子句:筛选符合特定条件的元素;

LINQ 查询表达式包含多种子句,例如有:

  1. group by子句:对查询结果进行分组;
  2. Distinct:去除集合中的重复项。
  3. OrderBy/ThenBy:提供复合排序条件;
  4. Max/Min/Average/Sum:执行数学运算;
  5. Count:返回集合中项的数量;
  6. let 子句:引入范围变量存储子表达式结果;
  7. join 子句:连接多个数据源;

三、LINQ 查询的两种形式

LINQ 查询有两种不同的语法形式:

  1. 利用 System.Linq.Enumerable 类中定义的扩展方法和 Lambda 表达式进行查询;
  2. 类似于SQL语法,可读性更好。查询语句最终会被转换为查询方法。

例如有:

cs 复制代码
查询表达式语法(类似于 SQL)

var result = from element in collection
            where condition
            orderby element.Property ascending/descending
            select element;
cs 复制代码
方法链语法(扩展方法)

var result = collection
            .Where(element => condition)
            .OrderBy(element => element.Property)
            .Select(element => element);

四、LINQ 常见用法示例

(一) 筛选数据(Where)

cs 复制代码
List<int> numbers = new List<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

//查询所有偶数
var evenNumbers = from num int numbers
                    where num%2 == 0
                    select num;

//方法链式
var evenNumbers = numbers.Where(num => num%2 == 0);

(二) 投影数据(Select)

cs 复制代码
List<string> names = new List<string> { "Alice", "Bob", "Charlie" };

// 将每个名字转换为大写
var upperNames = from name in names
                 select name.ToUpper();

// 方法链形式
var upperNamesMethod = names.Select(name => name.ToUpper());

// 输出:ALICE, BOB, CHARLIE

(三) 排序数据(OrderBy/OrderByDescending)

cs 复制代码
List<int> numbers = new List<int> { 5, 3, 8, 1, 2 };

// 按升序排序
var sortedNumbers = from num in numbers
                    orderby num ascending  // 可省略 ascending
                    select num;

// 方法链形式
var sortedNumbersMethod = numbers.OrderBy(num => num);

// 输出:1, 2, 3, 5, 8

(四) 分组数据(GroupBy)

cs 复制代码
List<string> words = new List<string> { "apple", "banana", "avocado", "cherry" };

// 按首字母分组
var groups = from word in words
             group word by word[0] into g
             select new { Key = g.Key, Words = g };

// 方法链形式
var groupsMethod = words.GroupBy(word => word[0])
                        .Select(g => new { Key = g.Key, Words = g });

// 输出:
// Group 'a': apple, avocado
// Group 'b': banana
// Group 'c': cherry

(五) 连接操作(Join)

cs 复制代码
List<Person> people = new List<Person>
{
    new Person { Id = 1, Name = "Alice" },
    new Person { Id = 2, Name = "Bob" }
};

List<Address> addresses = new List<Address>
{
    new Address { PersonId = 1, City = "New York" },
    new Address { PersonId = 2, City = "London" }
};

// 内连接:关联人员和地址
var joined = from p in people
             join a in addresses on p.Id equals a.PersonId
             select new { Name = p.Name, City = a.City };

// 方法链形式
var joinedMethod = people.Join(
    addresses,
    p => p.Id,
    a => a.PersonId,
    (p, a) => new { Name = p.Name, City = a.City }
);

// 输出:
// Alice, New York
// Bob, London

五、LINQ 注意事项

(一) 延迟执行

LINQ 查询通常是延迟执行的,直到你迭代结果(如使用 foreach 或调用 ToList() )才会执行。

(二) 数据源支持

LINQ 可以用于任何实现 IEnumerable<T> 或 IQueryable<T> 的类型,包括集合、数据库上下文(如 Entity Framework)、XML 文档等。

相关推荐
geovindu11 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
小羊先生car15 小时前
RTOS-F429-HAL-(动/静态)任务的创建(2026/7/27)
开发语言·算法·c#
地球驾驶员16 小时前
NX二次开发C#-获取体的外表面
开发语言·c#
向夏威夷 梦断明暄17 小时前
从 Bun 的 Rust 重写,看 C# 如何重建 AI 基础设施层
人工智能·rust·c#
心平气和量大福大18 小时前
C#-WPF-控件-LiveChart图表-线性2(LineSeries)-数据绑定
开发语言·c#·wpf
海盗123419 小时前
微软技术周报2026-07-27
microsoft·c#·.net
code bean1 天前
【C#】 `Channel<T>` 深度解析:生产者-消费者模式的现代解法
数据结构·c#
吴可可1232 天前
C# CAD二次开发:合并首尾重合多段线
c#
EIP低代码平台2 天前
EIP低代码平台 - 应用管理 - 表单设计
低代码·c#·权限·工作流·netcore
czhc11400756632 天前
726:zoffset
c#