C#学习相关系列之Linq用法---where和select用法(二)

一、select用法

Linq中的select可以便捷使我们的对List中的每一项进行操作,生成新的列表。

cs 复制代码
var tt=list.select(p=>p+10);
//select括号内为List中的每一项,p+10即为对每一项的操作,即对每项都加10生成新的List

用法实例:

1、lambda表达式

cs 复制代码
int[] array = { 1,5,6,7,6,9,12,2,7,6,33};
List<int> l1 = new List<int>(array);
var t1 = l1.Select((p)=>p+10);
foreach (var item in t1)
{
     Console.WriteLine(item);
}

输出结果为:

2、Linq语法

cs 复制代码
            List<Student_1> stuList = new List<Student_1>()
            {
                new Student_1(){ID=1,Name="John",Chinese=92,Math=88,English=92},
                new Student_1(){ID=2,Name="Mary",Chinese=87,Math=94,English=82},
                new Student_1(){ID=3,Name="KangKang",Chinese=89,Math=91,English=96},
                new Student_1(){ID=4,Name="Maria",Chinese=88,Math=65,English=94},
                new Student_1(){ID=5,Name="Ben",Chinese=70,Math=91,English=82},
            };

            var t1 = from e in stuList select e.English;
            foreach (var item in t1)
            {
                Console.WriteLine(item);
            }

二、SelectMany用法

在C# Linq中,SelectMany方法用于将一个集合中的每个元素转换为另一个集合,并将所有转换后的集合合并为一个集合。

cs 复制代码
List<List<int>> list = new List<List<int>>()
{
    new List<int>() { 1, 2, 3 },
    new List<int>() { 4, 5, 6 },
    new List<int>() { 7, 8, 9 }
};

var result = list.SelectMany(x => x);

foreach (var item in result)
{
    Console.WriteLine(item);
}

三、where用法

where在Linq中主要进行对数据筛选,并且生成新的List。

cs 复制代码
            List<Student_1> stuList = new List<Student_1>()
            {
                new Student_1(){ID=1,Name="John",Chinese=92,Math=88,English=92},
                new Student_1(){ID=2,Name="Mary",Chinese=87,Math=94,English=82},
                new Student_1(){ID=3,Name="KangKang",Chinese=89,Math=91,English=96},
                new Student_1(){ID=4,Name="Maria",Chinese=88,Math=65,English=94},
                new Student_1(){ID=5,Name="Ben",Chinese=70,Math=91,English=82},
            };
            
            //lambda表达式 表达式内部填的是判断条件
            var t1 = stuList.Where(p => p.English == 88);
            // Linq 语句
            var t1 = from e in stuList where e.English == 82 select e;

需要注意的是Lambda表达式中不需要select结尾,但Linq 语句必须是select结尾否则报错

运行结果为:

参考文献:

C#的LINQ select查询、where过滤、group分组、join关联_c# t.select().join_小龙在山东的博客-CSDN博客

相关推荐
EnglishJun1 分钟前
ARM嵌入式学习(十八)--- Linux的内核编译和启动
linux·运维·学习
星幻元宇VR12 分钟前
VR旋转蛋椅:沉浸式安全科普新体验
科技·学习·安全·vr·虚拟现实
ZhiqianXia26 分钟前
PyTorch 学习笔记(12):ATen C++ 算子引擎的完整架构之旅
pytorch·笔记·学习
旖-旎28 分钟前
链表(两两交换链表中的节点)(2)
数据结构·c++·学习·算法·链表·力控
周杰伦fans33 分钟前
cad文件选项卡不见了怎么办?
c#
知识分享小能手37 分钟前
MongoDB入门学习教程,从入门到精通,MongoDB的分片管理(17)
数据库·学习·mongodb
世人万千丶39 分钟前
Flutter 框架跨平台鸿蒙开发 - 嫉妒分析器应用
学习·flutter·华为·开源·harmonyos·鸿蒙
llm大模型算法工程师weng1 小时前
Python敏感词检测方案详解
开发语言·python·c#
AI_零食1 小时前
Flutter 框架跨平台鸿蒙开发 - 社交断舍离应用
运维·服务器·学习·flutter·游戏·开源·harmonyos