凡科网之前做的网站在哪看,购物网站用户管理,最新军事动态最新消息视频,广州比较有名的网站建设公司前言在Dotnet开发过程中#xff0c;Concat作为IEnumerable的扩展方法#xff0c;十分常用。本文对Concat方法的关键源码进行简要分析#xff0c;以方便大家日后更好的使用该方法。使用Concat 连接两个序列。假如我们有这样的两个集合#xff0c;我们需要把两个集合进行连接… 前言在Dotnet开发过程中Concat作为IEnumerable的扩展方法十分常用。本文对Concat方法的关键源码进行简要分析以方便大家日后更好的使用该方法。使用Concat 连接两个序列。假如我们有这样的两个集合我们需要把两个集合进行连接Liststring lst new Liststring { 张三, 李四 };
Liststring lst2 new Liststring { 王麻子 };不使用Linq大概会这样写private Liststring Concat(Liststring first, Liststring second){if (first null){throw new Exception(first is null);}if (second null){throw new Exception(second is null);}Liststring lstAll new Liststring();foreach (var item in first){lstAll.Add(item);}foreach (var item in second){lstAll.Add(item);}return lstAll;}使用Linqlst.Concat(lst2);源码解析方法public static IEnumerableTSource ConcatTSource(this IEnumerableTSource first, IEnumerableTSource second)参数first 要连接的第一个序列。second 要连接的第二个序列。返回值IEnumerable TSource 一个包含两个输入序列的连接元素的 IEnumerable T。此方法通过使用延迟执行来实现,因为IEnumerable是延迟加载的每次访问的时候才取值。所以我们在返回数据时需要使用yield所以我们可通过使用 foreach 语句从迭代器方法返回的序列。foreach 循环的每次迭代都会调用迭代器方法。迭代器方法运行到 yield return 语句时会返回一个 expression并保留当前在代码中的位置。下次调用迭代器函数时将从该位置重新开始执行。源码:public static IEnumerableTSource ConcatTSource(this IEnumerableTSource first, IEnumerableTSource second){if (first null){throw new Exception(first is null);}if (second null){throw new Exception(second is null);}foreach (TSource item in first){yield return item;}foreach (TSource item2 in second){yield return item2;}}总结本次通过分析Concat代码,进一步了解了迭代器与yield。