惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
V
V2EX
小众软件
小众软件
MongoDB | Blog
MongoDB | Blog
Jina AI
Jina AI
G
Google Developers Blog
H
Help Net Security
Microsoft Azure Blog
Microsoft Azure Blog
月光博客
月光博客
The GitHub Blog
The GitHub Blog
Y
Y Combinator Blog
爱范儿
爱范儿
B
Blog
云风的 BLOG
云风的 BLOG
H
Hackread – Cybersecurity News, Data Breaches, AI and More
GbyAI
GbyAI
博客园 - 叶小钗
aimingoo的专栏
aimingoo的专栏
Blog — PlanetScale
Blog — PlanetScale
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
有赞技术团队
有赞技术团队
博客园_首页
Google DeepMind News
Google DeepMind News
M
MIT News - Artificial intelligence

博客园 - 赶路人之刚出发

集成WebSecurity的Authorize进行身份验证时,数据库连接报错问题 Html.ActionLink传递参数 Automapper结合EF实现insert,update方法 MVC中使用RemoteAttribute异步远程验证 Html.RenderPartial WebMatrix.WebSecurity创建自定义用户属性 强类型view中List<Model〉问题 ViewBag任意属性的实现方法 params关键字 配置LINQ中的datacontext的log路径,以记录datacontext执行了的查询sql SortedList LINQ join/left join/cross join/group by/group join/sortedlist/cast Linq to objects示例 Lamda表达式 IDisposable 匿名类型与扩展方法 对象初始化器和集合初始化器 C#自动属性 .net random伪随机数
yield return 和 Func
赶路人之刚出发 · 2013-04-24 · via 博客园 - 赶路人之刚出发

yield return 用以生成IEnumerable类型的结果集,如下例所示,当第15行之行时,函数MyWhere并不会执行,而当第18行之行时会从第5行开始执行,在找到第一个偶数2时,函数MyWhere返回,执行第18行打印数字2,然后再调用第5行找到第二个偶数4,MyWhere又返回,继续执行第18行打印数字4。当执行到第22行时,函数MyWhere又会重新一次一次的执行。

MyWhere是为IEnumerable<T>类型定义的一个扩展方法,比如List<int>就是实现了IEnumerable的泛型方法,即可自动调用MyWhere这个扩展方法。

Func<T,bool> predicate表示predicate是一个可以指向一个有一个类型为T的参数且返回bool的匿名方法

 1 static class MyExtendClass
 2     {
 3         public static IEnumerable<T> MyWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate)
 4         {            
 5             foreach (T obj in source)
 6                 if (predicate(obj))
 7                     yield return obj;
 8         }
 9     }
10     class Program
11     {        
12         static void Main(string[] args)
13         {
14             List<int> myList = new List<int>() { 1, 2, 3, 4, 5, 6 };
15             var queryint= myList.MyWhere(x => x % 2 == 0);
16             foreach (var item in queryint)
17             {
18                 Console.Write(item);
19             }
20             foreach (var item in queryint)
21             {
22                 Console.Write(item);
23             }

Func在.net中定义如下:

// 摘要:
    //     封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
    //
    // 参数:
    //   arg:
    //     此委托封装的方法的参数。
    //
    // 类型参数:
    //   T:
    //     此委托封装的方法的参数类型。
    //
    //   TResult:
    //     此委托封装的方法的返回值类型。
    //
    // 返回结果:
    //     此委托封装的方法的返回值。
    [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
    public delegate TResult Func<in T, out TResult>(T arg);