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();
相关推荐
f狐0狸x9 小时前
【C++修炼之路】C++ list容器基本用法详解
开发语言·c++·list
坚持就完事了9 小时前
Java的OOP
java·开发语言
jllllyuz9 小时前
基于MATLAB的锂电池物理对象建模实现
开发语言·matlab
MyBFuture9 小时前
C#数组详解:一维二维与交错数组
开发语言·windows·c#·visual studio·vision pro
程序 代码狂人10 小时前
CentOS7初始化配置操作
linux·运维·开发语言·php
从此不归路10 小时前
Qt5 进阶【13】桌面 Qt 项目架构设计:从 MVC/MVVM 到模块划分
开发语言·c++·qt·架构·mvc
zhangx1234_10 小时前
C语言 数据在内存中的存储
c语言·开发语言
星空露珠10 小时前
速算24点检测生成核心lua
开发语言·数据库·算法·游戏·lua
老蒋每日coding10 小时前
Python3基础练习题详解,从入门到熟练的 50 个实例(一)
开发语言·python
历程里程碑10 小时前
Linux15 进程二
linux·运维·服务器·开发语言·数据结构·c++·笔记