在 IEnumerable 的元素内包含的列表上调用 .Count

Invoking .Count on a list contained inside an element of an IEnumerable

在我的代码中有一个 IEnumerable:

IEnumerable<SomeType> listOfSomething = MethodWhichReturnsAnIEnumerable(param 1)

现在,listOfSomething 中的每个元素还包含一个列表,我们称它为 listOfRules。我需要 return listOfSomething 中的元素 listOfRules:

中有 >0 个元素
var result = listOfSomething.Where(x => x.listOfRules.Count > 0);

这对性能意味着什么? listOfRules 是一个 List,所以我很好奇调用 Count 会对 IEnumerable listOfSomething 做什么,是否会将所有内容都放入内存。

因为listOfRulesList,查询Count属性非常快,因为对于List它只是returns的值私有字段,而不是每次都迭代整个集合。这是一个实现,取自 here:

// Read-only property describing how many elements are in the List.
public int Count {
    get {
        Contract.Ensures(Contract.Result<int>() >= 0);
        return _size; 
    }
}

如果 listOfRules 是一个 List<T>,使用 Count 将只是 return 存储的值,它不会枚举集合。它与 listOfSomething 无关,listOfSomething 将被枚举并且 Count 属性 将在每个 list.So 上被调用,没有什么可担心的。

list.Count只是returns一个字段的取值所以是非常快的。 O(1) 所以你的整体表现将是 O(N),其中 N 是 listOfSomething.

中的记录数