C# --- LINQ(Language Integrated Query)

LINQ(语言集成查询)是C#中用于操作数据的一种强大且灵活的方式。它提供了一种统一的语法来查询和操作不同类型的数据源,如集合、数据库、XML等。

目录

[7.1 基本概念](#7.1 基本概念)

[7.2 LINQ to SQL](#7.2 LINQ to SQL)

[7.3 LINQ to XML](#7.3 LINQ to XML)

[7.4 小结](#7.4 小结)


7.1 基本概念

> LINQ:提供了一组用于查询和操作数据的标准方法和运算符。

> 数据源:可以是数组、集合、数据库、XML文档等。

> 查询:使用LINQ查询语法或方法语法编写,用于筛选、排序、分组和投影数据。

7.1.1 示例:基本LINQ查询

7.1.1.1 示例数据

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

7.1.1.2 查询语法

cs 复制代码
var evenNumbers = from num in numbers
    where num % 2 == 0
    select num;

foreach (var num in evenNumbers)
{
    Console.WriteLine(num);//2,4,6,8,10
}

7.1.1.3 方法语法

cs 复制代码
var evenNumbers = numbers.Where(num => num % 2 == 0);

foreach (var num in evenNumbers)
{
    Console.WriteLine(num);
}

7.1.1.4 常用LINQ方法

> Where:筛选数据

> Select:投影数据

> OrderBy/OrderByDescending:排序

> GroupBy:分组

> Join:连接

> Aggregate:聚合操作

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int DepartmentId { get; set; }
}

public class Department
{
    public string Name { get; set; }
    public int Id { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Person> people = new List<Person>
        {
            new Person { Name = "Alice", Age = 30, DepartmentId = 1 },
            new Person { Name = "Bob", Age = 25, DepartmentId = 2 },
            new Person { Name = "Charlie", Age = 35, DepartmentId = 1 }
        };
        // Where
        var adults = people.Where(p => p.Age >= 30);
        Console.WriteLine("Adults:");
        foreach (var person in adults)
        {
            Console.WriteLine($"{person.Name} ({person.Age})");
        }

        // Adults:
        // Alice (30)
        // Charlie (35)

        // Select
        var names = people.Select(p => p.Name);
        Console.WriteLine("\nNames:");
        foreach (var name in names)
        {
            Console.WriteLine(name);
        }
        // Names:
        // Alice
        // Bob
        // Charlie

        // OrderBy
        var sortedByAge = people.OrderBy(p => p.Age);
        Console.WriteLine("\nSorted by Age:");
        foreach (var person in sortedByAge)
        {
            Console.WriteLine($"{person.Name} ({person.Age})");
        }
        // Sorted by Age:
        // Bob (25)
        // Alice (30)
        // Charlie (35)

        // GroupBy
        var groupedByAge = people.GroupBy(p => p.Age);
        Console.WriteLine("\nGrouped by Age:");
        foreach (var group in groupedByAge)
        {
            Console.WriteLine($"Age Group: {group.Key}");
            foreach (var person in group)
            {
                Console.WriteLine($"  {person.Name}");
            }
        }
        // Grouped by Age:
        // Age Group: 25
        //   Bob
        // Age Group: 30
        //   Alice
        // Age Group: 35
        //   Charlie


        // Join
        List<Department> departments = new List<Department>
        {
            new Department { Name = "HR", Id = 1 },
            new Department { Name = "IT", Id = 2 }
        };
        var employeeDepartments = from p in people
               join d in departments on p.DepartmentId equals d.Id
               select new { p.Name, Department = d.Name };

        Console.WriteLine("\nEmployee Departments:");
        foreach (var item in employeeDepartments)
        {
            Console.WriteLine($"{item.Name} works in {item.Department}");
        }
        // Employee Departments:
        // Alice works in HR
        // Charlie works in HR
        // Bob works in IT

    }

}

7.2 LINQ to SQL

LINQ不仅可以用于内存中的数据,还可以用于数据库查询。通过LINQ to SQL,可以使用LINQ查询数据库。

7.2.1 示例:LINQ to SQL

cs 复制代码
using (var context = new MyDataContext())
{
    var query = from p in context.People
        where p.Age >= 30
        select p;

    //---
    foreach (var person in query)
    {
        Console.WriteLine(person.Name);
    }
}

7.3 LINQ to XML

LINQ还可以用于查询和操作XML文档。

7.3.1 示例:LINQ to XML

cs 复制代码
XDocument doc = XDocument.Load("people.xml");
var query = from p in doc.Descendants("person")
        where (int)p.Element("age") >= 30
        select p;

foreach (var person in query)
{
    Console.WriteLine(person.Element("name").Value);
}

7.4 小结

> LINQ:提供了一种统一的方式来查询和操作不同的数据源。

> 查询语法和方法语法:两种编写LINQ查询的方式,查询语法类似于SQL,方法语法使用扩展方法。

> 常用方法:如 Where, Select, OrderBy, GroupBy, Join 等。

> LINQ to SQL 和 LINQ to XML:分别用于查询数据库和XML文档。

相关推荐
程序设计实验室1 小时前
一次小而美的重构:使用 C# 在 Avalonia 中生成真正好看的词云
c#
电商api接口开发2 小时前
ASP.NET MVC 入门指南二
前端·c#·html·mvc
我的golang之路果然有问题5 小时前
速成GO访问sql,个人笔记
经验分享·笔记·后端·sql·golang·go·database
Thomas_YXQ5 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
o0向阳而生0o5 小时前
28、.NET 中元数据是什么?
microsoft·c#·.net
niuTaylor6 小时前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#
军训猫猫头6 小时前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
秃头佛爷6 小时前
常用SQL整理
数据库·sql
浩浩测试一下8 小时前
SQL注入高级绕过手法汇总 重点
数据库·sql·安全·web安全·网络安全·oracle·安全架构
冰茶_8 小时前
.NET MAUI 发展历程:从 Xamarin 到现代跨平台应用开发框架
学习·microsoft·微软·c#·.net·xamarin