c# - Concat() 实际上如何加入较低级别的集合?

标签 c# linq collections

Linq 实际上在做什么?

最佳答案

(我假设这是针对 LINQ to Objects 的。其他任何内容都将以不同的方式实现:)

它只是返回第一个的所有内容,然后返回第二个的所有内容。所有数据都是流式传输的。像这样:

public static IEnumerable<T> Concat(this IEnumerable<T> source1,
    IEnumerable<T> source2)
{
    if (source1 == null)
    {
        throw new ArgumentNullException("source1");
    }
    if (source2 == null)
    {
        throw new ArgumentNullException("source1");
    }
    return ConcatImpl(source1, source2);
}


private static IEnumerable<T> ConcatImpl(this IEnumerable<T> source1,
    IEnumerable<T> source2)
{
    foreach (T item in source1)
    {
        yield return item;
    }
    foreach (T item in source2)
    {
        yield return item;
    }
}

我已将其拆分为两种方法,以便可以快速执行参数验证,但我仍然可以使用迭代器 block 。 (在对结果第一次调用 MoveNext() 之前,不会执行迭代器 block 中的任何代码。)

关于c# - Concat() 实际上如何加入较低级别的集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2828268/

相关文章:

c# - 您可以禁用 ServiceStack AutoQuery 的计数(总计)吗?

c# - 'IEnumerable< >' does not contain a definition for ' ' 并且找不到接受类型为 '' 的第一个参数的扩展方法 'IEnumerable<>'

c# - 使用 linq 在 IGrouping 中查找重复项

java - 找出另一个数组列表中不存在的数组列表的元素

java - 涉及集合和集合的类型不匹配

c# - 如何在 C# 中找出蓝牙设备的 COM 端口号?

c# - 变量名 '@' 已经声明。变量名称在查询批处理或存储过程中必须是唯一的

java - 如何删除和更新 TreeSet 中的已排序元素?

c# - 为什么按钮的 .CausesValidation 默认设置为 True?

c# - 在 linq 中指定带有左外连接的计数列