C#常用LINQ

在开发时发现别人的代码使用到了LINQ十分便捷且清晰,这里记录一下常用LINQ和对应的使用。参考链接:LINQ 菜鸟教程

使用的学生类和字符串用于测试

csharp 复制代码
public class Student
{
    public int StudentID;
    public string StudentName;
    public int Age;
}

Student[] studentArray = { 
            new Student() { StudentID = 1, StudentName = "John", Age = 18 },
            new Student() { StudentID = 2, StudentName = "Steve",  Age = 21 },
            new Student() { StudentID = 3, StudentName = "Bill",  Age = 25 },
            new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 },
            new Student() { StudentID = 5, StudentName = "Ron" , Age = 31 },
            new Student() { StudentID = 6, StudentName = "Chris",  Age = 17 },
            new Student() { StudentID = 7, StudentName = "Rob",Age = 19  },
        };

IList<string> stringList = new List<string>() { 
            "C# Tutorials",
            "VB.NET Tutorials",
            "Learn C++",
            "MVC Tutorials" ,
            "Java" 
        };

Where过滤

1.使用LINQ查找青少年学生

csharp 复制代码
Students = studentArray.Where(s => s.Age >= 18 && s.Age <= 25).ToList();

2.使用LINQ查找名字为Bill的第一位学生

csharp 复制代码
st1 = studentArray.Where(s => s.StudentName == "Bill").FirstOrDefault();

更加简便的写法:

其中对于 FirstOrDefault 和 First 的区别:FirstOrDefault 找不到返回默认值,First 找不到抛出异常

csharp 复制代码
st1 = studentArray.FirstOrDefault(s => s.StudentName == "Bill");
st1 = studentArray.First(s => s.StudentName == "Bill");

3.使用LINQ查找StudentID为5的学生

csharp 复制代码
st2 = studentArray.FirstOrDefault(s => s.StudentID == 5);

Single 和First 的区别:Single如果查找的元素不唯一会引发异常。Single会迭代所有元素,First满足第一个元素就返回

csharp 复制代码
st2 = studentArray.SingleOrDefault(s => s.StudentID == 5);

SingleOrDefault和Single区别:类似于 FirstOrDefault 和 First 的区别同上,这里不多赘述

csharp 复制代码
st2 = studentArray.Single(s => s.StudentID == 5);

Select投射

1.查询包含 Tutorials 的字符串

csharp 复制代码
strResult = stringList.Where(s => s.Contains("Tutorials")).ToList();

2.为字符串数组加 【】 包含起来

csharp 复制代码
strResult = stringList.Select(s => "【" + s + "】").ToList();

3.筛选 Tutorials 的字符串,添加 【】 输出

csharp 复制代码
strResult = stringList.Where(s => s.Contains("Tutorials")).Select(s => "【" + s + "】").ToList();

OrderBy排序

1.根据年龄进行排序

csharp 复制代码
Students = studentArray.OrderBy(s => s.Age).ToList();
相关推荐
xvhao2013几秒前
C++freopen的用法
开发语言·c++
co_wait9 分钟前
【C语言】字符串处理函数
c语言·开发语言
fie888911 分钟前
C# 文件分割与合并工具设计与实现
开发语言·c#
激昂网络13 分钟前
用CT001解读Type-C线材设计:为什么只有一个CC灯亮?
c语言·开发语言·嵌入式硬件
soragui15 分钟前
【Python】第 2 章:Python 对象模型
开发语言·python
攒了一袋星辰25 分钟前
SequenceGenerator废弃序列号异步补偿机制技术实现方案
java·开发语言·数据库·mysql
大黄说说27 分钟前
Java集合框架深度解析:ArrayList与LinkedList的底层博弈
开发语言
南境十里·墨染春水27 分钟前
C++ 笔记 仿函数(函数对象)
开发语言·c++·笔记
wjs202433 分钟前
MongoDB 索引限制
开发语言
AI精钢42 分钟前
Claude Certification 出现了一道“官方文档级”错题:关于 Claude Code Skills 优先级的误导
java·开发语言·工程实践·claude code·ai coding·agent skills·技术认证