C#-Linq源码解析之Concat

前言

在Dotnet开发过程中,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)
参数
  • first 要连接的第一个序列。
  • second 要连接的第二个序列。
返回值
  • IEnumerable< TSource > 一个包含两个输入序列的连接元素的 IEnumerable< T>。

此方法通过使用延迟执行来实现,因为IEnumerable是延迟加载的,每次访问的时候才取值。所以我们在返回数据时需要使用yield

所以我们可通过使用 foreach 语句从迭代器方法返回的序列。foreach 循环的每次迭代都会调用迭代器方法。迭代器方法运行到 yield return 语句时,会返回一个 expression,并保留当前在代码中的位置。下次调用迭代器函数时,将从该位置重新开始执行。

源码:
 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。