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();
相关推荐
Hello.Reader33 分钟前
Kafka 授权与 ACL 深入实践
分布式·kafka·linq
菜鸟plus+1 小时前
Captcha
java·开发语言
hqwest1 小时前
QT肝8天13--删除用户
开发语言·c++·qt·csdn开发云·列表分页·qt分页
李小白661 小时前
python 函数
开发语言·python
惬意小西瓜1 小时前
3.java常用类知识点
java·开发语言·分类
疯狂的Alex2 小时前
【C#避坑实战系列文章15】C# WinForm 上位机开发:解决串口粘包+LiveCharts卡顿+InfluxDB存储(免费代码+仿真工具)
sqlite·c#·上位机·串口通信·livechars·c#硬件对接
hqwest2 小时前
QT肝8天08--主界面设计
开发语言·qt·上位机·qt开发·ui设计
席万里2 小时前
使用Go做一个分布式短链系统
开发语言·分布式·golang
做运维的阿瑞3 小时前
Python核心架构深度解析:从解释器原理到GIL机制全面剖析
开发语言·python·架构·系统架构