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();
相关推荐
19H4 小时前
Flink-Source算子状态恢复分析
c#·linq
weixin_472339465 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击6 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue7 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
m0_555762908 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
浪裡遊9 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
lzb_kkk9 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼10 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
简佐义的博客10 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang