C#怎么使用LINQ查询 C# LINQ to Objects查询方法

来源:Vuejs社区作者:清原小日向头衔:网络博主
导读:本期聚焦于小伙伴创作的《C#怎么使用LINQ查询 C# LINQ to Objects查询方法》,敬请观看详情,探索知识的价值。以下视频、文章将为您系统阐述其核心内容与价值。如果您觉得《C#怎么使用LINQ查询 C# LINQ to Objects查询方法》有用,将其分享出去将是对创作者最好的鼓励。

在C#开发过程中,LINQ(语言集成查询)为开发者提供了统一的数据查询方式,其中LINQ to Objects是面向内存中集合对象的查询方案,支持对数组、列表等实现了IEnumerable接口的对象进行高效查询。它不需要额外的查询引擎,直接基于.NET运行时提供的功能实现数据筛选、排序、分组等操作,是日常业务开发里使用频率很高的功能。

C#怎么使用LINQ查询 C# LINQ to Objects查询方法

LINQ to Objects的基础使用方式

LINQ to Objects支持两种语法形式,分别是查询语法和方法语法,两者最终都会被编译器转换为方法调用,功能上基本等价,开发者可以根据个人习惯选择使用。

查询语法示例

查询语法更接近SQL的书写风格,可读性较强,适合复杂的查询逻辑。以下是一个从整数列表中筛选偶数的示例:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // 查询语法:筛选偶数
        var evenNumbers = from num in numbers
                          where num % 2 == 0
                          select num;
        Console.WriteLine("偶数结果:");
        foreach (var num in evenNumbers)
        {
            Console.Write(num + " ");
        }
        // 输出:2 4 6 8 10
    }
}

方法语法示例

方法语法基于扩展方法实现,链式调用的风格更适合简单的查询逻辑,以下是同样筛选偶数的方法语法实现:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        // 方法语法:筛选偶数
        var evenNumbers = numbers.Where(num => num % 2 == 0);
        Console.WriteLine("偶数结果:");
        foreach (var num in evenNumbers)
        {
            Console.Write(num + " ");
        }
        // 输出:2 4 6 8 10
    }
}

常用LINQ to Objects查询方法

除了基础的Where筛选方法,LINQ还提供了多种常用的查询方法,覆盖排序、分组、投影、聚合等场景。

排序方法

OrderByOrderByDescending用于升序和降序排序,ThenByThenByDescending用于多条件排序。以下示例对学生列表按年龄升序、分数降序排序:

using System;
using System.Collections.Generic;
using System.Linq;

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int Score { get; set; }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "张三", Age = 18, Score = 85 },
            new Student { Name = "李四", Age = 17, Score = 90 },
            new Student { Name = "王五", Age = 18, Score = 92 }
        };
        // 按年龄升序,年龄相同按分数降序排序
        var sortedStudents = students.OrderBy(s => s.Age).ThenByDescending(s => s.Score);
        Console.WriteLine("排序后的学生列表:");
        foreach (var student in sortedStudents)
        {
            Console.WriteLine($"姓名:{student.Name},年龄:{student.Age},分数:{student.Score}");
        }
    }
}

分组方法

GroupBy可以按照指定条件对数据进行分组,返回分组后的结果集合。以下示例将学生按年龄分组:

using System;
using System.Collections.Generic;
using System.Linq;

class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "张三", Age = 18 },
            new Student { Name = "李四", Age = 17 },
            new Student { Name = "王五", Age = 18 }
        };
        // 按年龄分组
        var groups = students.GroupBy(s => s.Age);
        Console.WriteLine("分组结果:");
        foreach (var group in groups)
        {
            Console.WriteLine($"年龄:{group.Key},成员:{string.Join("、", group.Select(s => s.Name))}");
        }
    }
}

聚合方法

LINQ提供了CountSumAverageMaxMin等聚合方法,用于统计数据。以下示例计算学生分数的相关统计值:

using System;
using System.Collections.Generic;
using System.Linq;

class Student
{
    public string Name { get; set; }
    public int Score { get; set; }
}

class Program
{
    static void Main()
    {
        List<Student> students = new List<Student>
        {
            new Student { Name = "张三", Score = 85 },
            new Student { Name = "李四", Score = 90 },
            new Student { Name = "王五", Score = 92 }
        };
        Console.WriteLine($"学生总数:{students.Count()}");
        Console.WriteLine($"总分:{students.Sum(s => s.Score)}");
        Console.WriteLine($"平均分:{students.Average(s => s.Score)}");
        Console.WriteLine($"最高分:{students.Max(s => s.Score)}");
        Console.WriteLine($"最低分:{students.Min(s => s.Score)}");
    }
}

使用注意事项

  • LINQ查询默认是延迟执行的,只有当遍历查询结果时,才会真正执行查询逻辑,如果需要立即执行,可以调用ToListToArray等方法。
  • 查询语法的可读性更强,适合复杂的多条件查询;方法语法更灵活,适合简单的链式调用场景,开发者可以根据实际需求选择。
  • 在使用Lambda表达式作为查询条件时,注意避免复杂的逻辑嵌套,否则会降低代码的可读性。

LINQ C# LINQ_to_Objects 查询方法修改时间:2026-07-02 03:48:17

免责声明:​ 已尽一切努力确保本网站所含信息的准确性。网站内容多为原创整理与精心编撰,观点力求客观中立。本站旨在免费分享,内容仅供个人学习、研究或参考使用。若引用了第三方作品,版权归原作者所有。如内容涉及您的权益,请联系我们处理。
内容垂直聚焦
专注技术核心技术栏目,确保每篇文章深度聚焦于实用技能。从代码技巧到架构设计,为用户提供无干扰的纯技术知识沉淀,精准满足专业提升需求。
知识结构清晰
覆盖从开发到部署的全链路。AI、前端、编程、数据库、服务器、建站、系统层层递进,构建清晰学习路径,帮助用户系统化掌握开发与运维所需的核心技术。
深度技术解析
拒绝泛泛而谈,深入技术细节与实践难点。无论是数据库优化还是服务器配置,均结合真实场景与代码示例进行剖析,致力于提供可直接应用于工作的解决方案。
专业领域覆盖
精准对应开发生命周期。从前端界面到后端编程,从数据库操作到服务器运维,形成完整闭环,一站式满足全栈工程师和运维人员的技术需求。
即学即用高效
内容强调实操性,步骤清晰、代码完整。用户可根据教程直接复现和应用于自身项目,显著缩短从学习到实践的距离,快速解决开发中的具体问题。
持续更新保障
专注既定技术方向进行长期、稳定的内容输出。确保各栏目技术文章持续更新迭代,紧跟主流技术发展趋势,为用户提供经久不衰的学习价值。