我有以下场景,我想将一些项目添加到列表中......
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/