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();
相关推荐
chao_78941 分钟前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
尘世闲鱼2 小时前
解数独(C++版本)
开发语言·c++·算法·解数独
纨妙3 小时前
python打卡day59
开发语言·python
wuxuanok3 小时前
Web后端开发-请求响应
java·开发语言·笔记·学习
Sally璐璐3 小时前
IPSAN 共享存储详解:架构、优化与落地实践指南
开发语言·php
像风一样的男人@4 小时前
python --货车装厢问题
开发语言·python
Humbunklung4 小时前
Rust枚举:让数据类型告别单调乏味
开发语言·后端·rust
Y1nhl4 小时前
力扣_链表_python版本
开发语言·python·算法·leetcode·链表·职场和发展
OEC小胖胖4 小时前
深入理解 Vue.js 响应式原理及其在 Web 前端开发中的应用
开发语言·前端·javascript·vue.js·web