C#-Linq源碼解析之Concat
前言
在Dotnet開發(fā)過程中,Concat作為IEnumerable的擴展方法,十分常用。本文對Concat方法的關鍵源碼進行簡要分析,以方便大家日后更好的使用該方法。
使用
Concat 連接兩個序列。
假如我們有這樣的兩個集合,我們需要把兩個集合進行連接!
List<string> lst = new List<string> { "張三", "李四" };
List<string> lst2 = new List<string> { "王麻子" };
不使用Linq
大概會這樣寫!
private List<string> Concat(List<string> first, List<string> second)
{
if (first == null)
{
throw new Exception("first is null");
}
if (second == null)
{
throw new Exception("second is null");
}
List<string> lstAll = new List<string>();
foreach (var item in first)
{
lstAll.Add(item);
}
foreach (var item in second)
{
lstAll.Add(item);
}
return lstAll;
}
使用Linq
lst.Concat(lst2);
源碼解析
方法
public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
參數(shù)
first 要連接的第一個序列。 second 要連接的第二個序列。
返回值
IEnumerable< TSource > 一個包含兩個輸入序列的連接元素的 IEnumerable< T>。
此方法通過使用延遲執(zhí)行來實現(xiàn),因為IEnumerable是延遲加載的,每次訪問的時候才取值。所以我們在返回數(shù)據(jù)時需要使用yield
所以我們可通過使用 foreach 語句從迭代器方法返回的序列。foreach 循環(huán)的每次迭代都會調(diào)用迭代器方法。迭代器方法運行到 yield return 語句時,會返回一個 expression,并保留當前在代碼中的位置。下次調(diào)用迭代器函數(shù)時,將從該位置重新開始執(zhí)行。
源碼:
public static IEnumerable<TSource> Concat<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> 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。
評論
圖片
表情
