net lambda 、 匿名函数 以及集合(实现IEnumerable的 如数组 、list等)

匿名函数:》》》

Action a1 = delegate(int i) { Console.WriteLine(i); };

Lambda:>>>

Aciont a1= (int i) => { Console.WriteLine(i); };

可以简写 (编译器会自动根据委托类型 推断)

Action a1 = (i)=> { Console.WriteLine(i); };

还可以简写 如果只有一个参数,可以把括号省略

Action a1 = i=> { Console.WriteLine(i); };

如果委托有返回值,并且方法体只有一个行代码,且这行代码还是返回值, 则可以 省略 大括号 和 return

Func f1 => () => { return 5;};

可以简写》》》》

Func f1 => () => 5;

csharp 复制代码
 static class Zen
 {

     public static IEnumerable<T> myWhere<T>(this IEnumerable<T> datas, Func<T, bool> func) {
         List<T> resultList = new List<T>();
         foreach (T  item in datas) 
         { 
             if (func(item))
                 resultList.Add(item);
         }
         return resultList;
     }
 }
 class Program
 {
    
    
     static void Main(string[] args)
     {

         int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

         //nums  数组中是3的倍数 提取出来
         IEnumerable<int> lt = nums.myWhere<int>((t) =>
         {
             if (t % 3 == 0)
                 return true;
             return false;
         });
         foreach (int i in lt) 
         {
             Console.WriteLine($"结果:{i}");
         }
         Console.ReadKey();
     }

   
 }

IEnumerable 对应的 扩展方法

where

select

Max

Min

OrderBy

First : 获取第一个,如果一个都没有,则抛出异常

FirstOrDefault : 获取第一个,如果一个都没有则返回默认值(如果是值类型,默认值0 如果是引用类型 则默认值 null)

Singe : 获取唯一一个,如果没有或者有多个,则抛出异常

SingeOrDefault : 获取唯一一个,如果没有则返回默认值,如果有多个,则抛出异常

相关推荐
缺点内向1 天前
C#: 告别繁琐!轻松移除Word文档中的文本与图片水印
c#·自动化·word·.net
2501_930707781 天前
使用 C# .NET 从 PowerPoint 演示文稿中提取背景图片
c#·powerpoint·.net
向上的车轮1 天前
为什么.NET(C#)转 Java 开发时常常在“吐槽”Java:checked exception
java·c#·.net
波波0071 天前
每日一题:.NET 的 GC是如何分代工作的?
算法·.net·gc
波波0072 天前
每日一题:中间件是如何工作的?
中间件·.net·面试题
无风听海3 天前
.NET 10之可空引用类型
数据结构·.net
码云数智-园园3 天前
基于 JSON 配置的 .NET 桌面应用自动更新实现指南
.net
无风听海3 天前
.NET 10 之dotnet run的功能
.net
岩屿3 天前
Ubuntu下安装Docker并部署.NET API(二)
运维·docker·容器·.net
码云数智-大飞3 天前
.NET 中高效实现 List 集合去重的多种方法详解
.net