C# Linq中 Where使用技巧

C# Linq中 Where使用技巧

hello 大家好,很开心又能重新分享C#编程开发技巧了,之前因为工作和生活没有达成一个很好的平衡,导致状态下滑,好像断更很久了。在这里不得自我检讨一波,以后继续分享~大家一起交流呀~.

你可能不知道的源码网站

.Net源码开源反编译工具 https://github.com/KirillOsenkov/SourceBrowser
在上面的地址里面有着查看源码的网页端工具,很方便大家学习我们巨硬大佬写的代码,赶紧Mark吧~

C# Linq中 Where使用技巧

Where 的基本使用

1            var array = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // 定义包含十个数据的数组
2            var data = array.Where(x => x % 2==0); // Where 条件里面过滤整数
3            foreach (var item in data)
4            {
5                Console.WriteLine(item); // 2,4,6,8,10
6            }

自定义Where 扩展函数

首先定义一个静态类 WhereExtension

 1public static IEnumerable<T> NewWhere<T> (this IEnumerable<T> items, Func<T,bool> func)
 2{
 3
 4   foreach (var item in items)
 5    {
 6       if(func(item))
 7         {
 8           yield return item; // yield 关键字的用法详细看上面视频
 9         }
10    }
11}

IEnumerable && yield 实现一个斐波那契数列(无需递归)

 1public static IEnumerable<int> GenarateFibonacci(int n)
 2{
 3     if(n== 0) yield break;
 4     if (n >= 1) yield return 1;
 5
 6     for (int i = 0,a=1,b=1; i < n-1; i++)
 7     {
 8        int temp = a + b;
 9        a = b;
10        b= temp;
11        yield return a;
12      }
13}

时间有限,还有很多语法骚操作并未分享,在后续的文章中会把所学所用的技巧都分享出来,希望可以一起进步!