检查 IEnumerable 是否仅包含一个元素的有效方法

And*_*NET 2 c# linq ienumerable

我有一个IEnumerableStream. 蒸汽可能非常大(想想 GB)。

我需要知道序列是否只包含一个元素。检查 if.Count() == 1效率不高,因为它会通过读取完整的流来枚举整个列表。使用.Any没有用,因为我需要知道它是否只包含一个元素,而不是它包含任何元素。

可能的解决方案

.Take(2).ToList()然后进行计数是否是检查序列是否只包含一个元素的最有效方法?

Cor*_*son 6

既然你要求“高效”,这样的事情将避免 LINQ 的一些分配开销

int HasOne<T>(this IEnumerable<T> collection)
{
    // avoid allocating an enumerator if possible.
    if (collection.TryGetNonEnumeratedCount(out int actualCount))
    {
        return actualCount == 1;
    }

    // avoid allocating the LINQ IEnumerables for Take().
    using IEnumerator<T> e = collection.GetEnumerator();
    return e.MoveNext() && !e.MoveNext();
}
Run Code Online (Sandbox Code Playgroud)


Dmi*_*nko 5

Take最多可以2拨打以下电话Count()

bool exactlyOne = source.Take(2).Count() == 1;
Run Code Online (Sandbox Code Playgroud)

在最坏的情况下,我们只会阅读前两项。