首页 > 编程语言 >C# LINQ 基础和常用的扩展方法

C# LINQ 基础和常用的扩展方法

时间:2023-11-26 18:22:23浏览次数:23  
标签:Salary Console C# employees 扩展 LINQ WriteLine Employee Id

1. 自定义Where方法

static void MM(string[] args)
{
    IEnumerable<int> ints = new int[] { 1, 2, 4, 63, 12, 34, 46, 12, 45, 12456 };
    // 使用LINQ中的Where方法
    //IEnumerable<int> ints2 = ints.Where(a => a > 10);
    // 使用自定义的Where方法
    IEnumerable<int> ints2 = MyWhere(ints, a => a > 10);
    foreach (int i in ints2)
    {
        Console.WriteLine(i);
    }
}
// 自定义的Where方法
static IEnumerable<int> MyWhere(IEnumerable<int> ints,Func<int,bool> f)
{
    List<int> list = new List<int>();
    foreach (int i in ints)
    {
        if (f(i))
        {
            yield return i;
        }
    }
}

2. 常用的方法

2.1 初始化数据集合
List<Employee> employees = new List<Employee>();
list.Add(new Employee(){Id = 1,Name = "张三",Age = 16,Gender = false,Salary = 2000});
list.Add(new Employee(){Id = 2,Name = "凌洋",Age = 32,Gender = false,Salary = 1500});
list.Add(new Employee(){Id = 3,Name = "夏一桐",Age = 11,Gender = true,Salary = 4000});
list.Add(new Employee(){Id = 4,Name = "崔今生",Age = 32,Gender = false,Salary = 2000});
list.Add(new Employee(){Id = 5,Name = "孙河",Age = 23,Gender = true,Salary = 5000});
list.Add(new Employee(){Id = 6,Name = "方晴",Age = 26,Gender = true,Salary = 8000});
list.Add(new Employee(){Id = 7,Name = "赵七",Age = 32,Gender = true,Salary = 3000});
list.Add(new Employee(){Id = 8,Name = "包卫丽",Age = 26 ,Gender = true,Salary = 4500});
2.2 Where

Where 获取满足条件的数据 返回值:IEnumerable<>集合

IEnumerable<Employee> employees1 = employees.Where(a => a.Salary > 3000 && a.Age > 30);
foreach (Employee employee in employees1)
{
    Console.WriteLine(employee.ToString());
}
2.3 Any

Any 判断集合中是否最少有一条满足他条件的数据 返回值:bool

Console.WriteLine(employees.Any(a => a.Id > 100));
Console.WriteLine(employees.Any(a => a.Id > 7));
2.4 Count

Count 获取集合中满足条件的数量 返回值:int

Console.WriteLine(employees.Count(a => a.Id > 100));
Console.WriteLine(employees.Count(a => a.Id > 7));
2.5 Single

Single 有并且只有一条满足条件的数据,有多条满足条件的数据提示错误,未找到满足条件的数据也会提示错误

//Employee employee1 = employees.Single(a=>a.Id>1); //报错
//Employee employee1 = employees.Single(a => a.Id == 11); //报错
Employee employee1 = employees.Single(a => a.Id == 1); // 正常
Console.WriteLine(employee1);
2.6 SingleOrDefault

SingleOrDefault 最多只有一条满足条件的数据,未找到满足条件的数据返回该数据类型的默认值

//Employee employee2 = employees.SingleOrDefault(a => a.Id > 1); //报错
//Employee employee2 = employees.SingleOrDefault(a => a.Id == 11); //正常
Employee employee2 = employees.SingleOrDefault(a => a.Id == 1); // 正常
Console.WriteLine(employee2);
2.7 First

First 最少有一条满足条件的数据,有多条满足条件的数据返回第一条,未找到满足条件的数据提示错误

//Employee employee3 = employees.First(a => a.Id > 2); // 正常
//Employee employee3 = employees.First(a => a.Id == 22); // 报错
Employee employee3 = employees.First(a => a.Id == 2); // 正常
Console.WriteLine(employee3);
2.8 FirstOrDefault

Where 获取满足条件的数据 返回值:IEnumerable<>集合

//Employee employee4 = employees.FirstOrDefault(a => a.Id > 2); // 正常
//Employee employee4 = employees.FirstOrDefault(a => a.Id == 22); // 正常
Employee employee4 = employees.FirstOrDefault(a => a.Id == 2); // 正常
Console.WriteLine(employee4);
2.9 OrderBy

OrderBy 正序排序

IEnumerable<Employee> employees2 = employees.OrderBy(a => a.Salary);
foreach (Employee employee in employees2)
{
    Console.WriteLine(employee);
}
2.10 OrderByDescending

OrderByDescending 倒序排序

IEnumerable<Employee> employees3 = employees.OrderByDescending(a => a.Salary);
foreach (Employee employee in employees3)
{
    Console.WriteLine(employee);
}
2.11 OrderBy().ThenBy

OrderBy().ThenBy 排序完后再进行小范围的排序

IEnumerable<Employee> employees4 = employees.OrderBy(a => a.Gender).ThenByDescending(a=>a.Salary).ThenBy(a=>a.Age);
foreach (Employee employee in employees4)
{
    Console.WriteLine(employee);
}
2.12 Skip

Skip 跳过多少条数据

IEnumerable<Employee> employees5 = employees.Where(a=>a.Gender==false).OrderBy(a=>a.Salary).Skip(1);
foreach (Employee employee in employees5)
{
    Console.WriteLine(employee);
}
2.13 Take

Take 取几条数据

IEnumerable<Employee> employees6 = employees.Where(a => a.Gender == false).OrderBy(a => a.Salary).Take(1);
foreach (Employee employee in employees6)
{
    Console.WriteLine(employee);
}
2.14 SKip+Take

SKip+Take 跳过几条取几条

IEnumerable<Employee> employees7 = employees.Where(a => a.Gender == false).OrderBy(a => a.Salary).Skip(1).Take(2);
foreach (Employee employee in employees7)
{
    Console.WriteLine(employee);
}
2.15 GroupBy + Max + Min + Average

GroupBy(g=>g) 分组,返回值是IEnumerable<IGrouping<g的类型, g的类型>>类型
Max(g=>g) 获取最大值 返回值是g的类型
Min(g=>g) 获取最小值 返回值是g的类型
Average(g=>g) 获取平均值 返回值是g的类型

IEnumerable<IGrouping<int, Employee>> employees1 = employees.OrderBy(e=>e.Age).GroupBy(e => e.Age);
foreach (IGrouping<int,Employee> g in employees1)
{
    Console.WriteLine(g.Key);
    Console.WriteLine("分组中的最大工资:"+g.Max(e=>e.Salary));
    Console.WriteLine("分组中的最小工资:" + g.Min(e=>e.Salary));
    Console.WriteLine("分组中的平均工资:" + g.Average(e=>e.Salary));
    Console.WriteLine("分组中数量:" + g.Count());
    foreach (Employee e in g)
    {
        Console.WriteLine(e);
    }
}
2.16 Select(映射)

Select 映射一种新的类型

var ls = employees.Select(a => new { XM = a.Name, NL = a.Age, XB = a.Gender ? "男" : "女" });
foreach (var e in ls)
{
    Console.WriteLine(e);
}

案例:根据年龄进行分组,获取每组中年龄、最大工资、最小工资、平均工资、和分组个数

var ls1 = employees.GroupBy(a => a.Age).Select(a => new { 
    Age = a.Key,
    MaxS = a.Max(g => g.Salary),
    MinS = a.Min(g=>g.Salary),
    AvgS = a.Average(g => g.Salary),
    Count = a.Count()
});
foreach (var e in ls1)
{
    Console.WriteLine(e);
}
3 实际应用题

获取字符串中成绩的平均值

string s = "61,90,100,99,18,22,38,66,80,93,55,50,89";
IEnumerable<string> l = s.Split(",");
Console.WriteLine(l.Average(a=>Convert.ToDouble(a)));

统计一个字符串中字母出现的频率(忽略大小写)然后按照从高到低的顺序输出频率高于2次的单词和出现的频率

string s = "KhKlkKHhfadsf  1111  JHLFDSdaskfjlLKHDSA";
var chars = s.Where(c=>char.IsLetter(c)).Select(c=>char.ToLower(c)).GroupBy(x => x).OrderByDescending(g=>g.Count()).Where(g=>g.Count() > 2).Select(c=>new { dc = c.Key,pl = c.Count()});
foreach (var c in chars)
{
    Console.WriteLine(c);
}

标签:Salary,Console,C#,employees,扩展,LINQ,WriteLine,Employee,Id
From: https://www.cnblogs.com/sunhouzi/p/17857639.html

相关文章

  • 第 2 篇 Scrum 冲刺博客
    一、作业概述这个作业属于哪个课程软件工程-计科21级12班-计算机学院-广东工业大学这个作业要求在哪里团队项目3-计科21级12班这个作业的目标进行敏捷冲刺开发二、站立式会议成员昨天已完成的工作今天计划完成的工作黄家宝答卷功能的设计答题的查......
  • WGCLOUD 基础详解 常用命令笔记
    WGCLOUD在v3.4.9版本新增了一个模块【常用命令笔记】这个模块非常有用,对我的工作非常有帮助,可以把我常用的一些命令或文档记录下来,也可以当作记事本使用,记录一些笔记使用简单,而且方便......
  • AtCoder Beginner Contest 322
    A-FirstABC2#include<bits/stdc++.h>usingnamespacestd;#defineintlonglong#definempmake_pairusingvi=vector<int>;usingpii=pair<int,int>;voidsolve(){intn;strings;cin>>n>>s;......
  • CentOS 7 安装Mysql环境
    Centos7下彻底删除Mysql,重新安装Mysql常用操作命令 启动mysql服务systemctlstartmysqld.service停止mysql服务systemctlstopmysqld.service重启mysql服务systemctlrestartmysqld.service查看mysql服务当前状态systemctlstatusmysqld.service 设置mysql服务开......
  • BlockingQueue阻塞队列
    BlockingQueue阻塞队列BlockingQueue简介juc包下,BlockingQueue很好的解决了多线程中,高效安全的"传输数据"问题。阻塞队列,是一个队列,可以是数据从队列的一端输入,从另一端输出。当队列空时,从队列获取元素线程被阻塞,直到其他线程向空的队列插入新元素。当队列满时,向队列添加元......
  • 使用xgboost的c接口推理模型
    title:使用xgboost的c接口推理模型banner_img:https://cdn.studyinglover.com/pic/2023/07/b5c4ecf9aa476ca1073f99b22fe9605e.jpgdate:2023-9-1021:10:00categories:-踩坑tags:-机器学习使用xgboost的c接口推理模型官方capitutorial和文档,非常恶心的一点是,tutor......
  • XCTF-Web_php_unserialize
    访问查看是一道经典的反序列化题目,尝试解题,大概一下脚本,需要传入var进行反序列化php代码会先将var传入的值进行base64解码,然后进行perg_match()正则匹配判断,如果匹配成立就执行die()方法终止脚本运行使用unserialize()方法反序列化我们传入的值__wakeup()在反序列化时候执......
  • Reference and inspiration from China's strategy for addressing water pollution i
     AccordingtoChina'sthreelineonepermitmeasures,webelievethatthishasacertainreferencevalueforwaterpollutionissuesinAfrica.The"threelines"referstotheecologicalprotectionredline,theenvironmentalqualitybottom......
  • 通过Java和ECDSA生成X509版本的证书
    1.创新maven项目导入相关依赖<dependencies><dependency><groupId>org.bouncycastle</groupId><artifactId>bcpkix-jdk15on</artifactId><version>1.70</version></depe......
  • CV中的一些名词
    202311201.Zero-shot定义:在测试时,遇到训练时未观察到的类的样本,并需要预测它们所属的类。通常通过某些形式的辅助信息将观察到的未观察到的类相关联来工作,该辅助信息对对象的可观察区别属性进行编码。2.体素MRI图像通常为三维图像,一个二维图像上的像素对应到三维图像上......