c# - 带有 IEnumerable<T> 参数的 List.AddRange 不起作用?

标签 c# list ienumerable deferred addrange

我有以下场景,我想将一些项目添加到列表中......

List<T> items = new List<T>();
IEnumerable<T> addItems = someCollection.Where(...);
items.AddRange(addItems);

使用此代码,没有任何项目添加到列表中,但如果我在 Linq 语句之后添加 .ToList(),则项目会正确添加。我猜这是由于延迟执行,但我认为给定 List.AddRange 函数接受一个 IEnumerable,它将枚举要添加的项目。

谁能解释一下为什么会这样?

最佳答案

I guess this is due to deferred execution but I would have thought that given the List.AddRange function accepts an IEnumerable that it would enumerate the items to be added.

确实如此。 ICollection<T> 短路(在这种情况下你不会点击),这会导致它使用 ICollection<T>.CopyTo 而不是枚举项目,否则,它将枚举集合。

对于一个工作示例,请尝试:

using System;
using System.Linq;
using System.Collections.Generic;

internal class Program
{
    private static List<T> RunQuery<T>(IEnumerable<T> someCollection, Func<T, bool> predicate)
    {
        List<T> items = new List<T>();
        IEnumerable<T> addItems = someCollection.Where(predicate);
        items.AddRange(addItems);
        return items;
    }

    static void Main()
    {
        var values = Enumerable.Range(0, 1000);

        List<int> results = RunQuery(values, i => i >= 500);

        Console.WriteLine(results.Count);
        Console.WriteLine("Press key to exit:");
        Console.ReadKey();
    }
}

这将使用您的确切代码,并将打印出 500(List<T> 中正确的项目数)。

关于c# - 带有 IEnumerable<T> 参数的 List.AddRange 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11750688/

相关文章:

c# - 为什么 "return"和 "yield return"不能在同一个方法中使用?

asp.net-mvc-3 - MVC3 Razor > Make Model IEnumerable,所以它可以在 View 中使用?

c# - 迭代 IEnumerable,特殊套管最后一个元素

C# - 水印密码字符?

c# - 如何在 Windows 窗体 C# 中执行代码时显示动画加载窗体

c# - 测试使用 HttpContext.Current.Request.Files 的 Web API 方法?

python - 为什么 Python `Memory Error` 和列表 `append()` 剩余大量 RAM

perl - Perl的 map 有什么意义?

c# - 仅调用泛型的基本方法

python - 拆分CSV文件后将数据放入列表中 - Python