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博客

相关推荐
Xudde.6 小时前
friendly靶机渗透
笔记·学习·安全·web安全·php
拼好饭和她皆失7 小时前
Java学习---Arrays类
java·开发语言·学习
代码游侠7 小时前
学习笔记——GDB调试工具
linux·开发语言·笔记·学习
行走的夜7 小时前
高质量测试用例设计:金字塔模型+系统化工作流+方法体系+改进机制
学习·测试用例
思成不止于此7 小时前
MySQL 约束详解:保证数据完整性的核心机制
数据库·笔记·学习·mysql
九千七5267 小时前
sklearn学习(5)线性回归和逻辑回归
人工智能·学习·机器学习·逻辑回归·线性回归·sklearn
职业码农NO.17 小时前
架构模型:企业架构、技术架构、C4模型、TOGAF、互联网模型优缺点分析与学习
学习·架构·系统架构·软件工程
走在路上的菜鸟7 小时前
Android学Dart学习笔记第九节 Patterns
android·笔记·学习·flutter
代码游侠7 小时前
学习笔记——栈
开发语言·数据结构·笔记·学习·算法
光头程序员8 小时前
学习笔记——vite 打包构建优化之tree shaking
笔记·学习