46

初期化された が与えられた場合IEnumerable:

IEnumerable<T> enumerable;

複数の要素があるかどうかを判断したいと思います。これを行う最も明白な方法は次のとおりだと思います。

enumerable.Count() > 1

ただし、コレクション全体Count()を列挙すると思いますが、これはこのユース ケースには不要です。たとえば、コレクションに非常に大量の要素が含まれているか、外部ソースからデータが提供されている場合、これはパフォーマンスの点で非常に無駄になる可能性があります。

2つ以上の要素を列挙せずにこれを行うにはどうすればよいですか?

4

4 に答える 4

62

System.Linq の拡張メソッドを組み合わせることで、さまざまな方法でこれをテストできます... 2 つの簡単な例を以下に示します。

bool twoOrMore = enumerable.Skip(1).Any();
bool twoOrMoreOther = enumerable.Take(2).Count() == 2;

Count() >= 1かどうかを確認する一般的な方法があるため、最初のものを好みAny()ます。したがって、読みやすくなります。

于 2013-06-24T23:49:31.480 に答える
5

面白いことに、Next() を 2 回呼び出してから、別の IEnumerable を取得します。

または、この特定の目標のために小さなラッパー クラスを作成EnumerablePrefetcher : IEnumerable<T>します。つまり、初期化時に指定された量のアイテムを取得しようとします。

そのIEnumerable<T> GetItems()メソッドは、この方法で yield return を使用する必要があります

foreach (T item in prefetchedItems) // array of T, prefetched and decided if IEnumerable has at least n elements
{
  yield return item;
}
foreach (T item in otherItems) // IEnumerable<T>
{
  yield return item;
}
于 2013-06-25T00:02:48.907 に答える
2

@ Cameron-Sのソリューションはよりシンプルですが、以下はより効率的です。Enumerable.Count()メソッドに基づいてこれを思いつきました。のカウントまたはタイプSkip()を取得するために、常に反復し、短絡しません。sourceICollectionICollection<T>

/// <summary>
/// Returns true if source has at least <paramref name="count"/> elements efficiently.
/// </summary>
/// <remarks>Based on int Enumerable.Count() method.</remarks>
public static bool HasCountOfAtLeast<TSource>(this IEnumerable<TSource> source, int count)
{
    source.ThrowIfArgumentNull("source");
    var collection = source as ICollection<TSource>;
    if (collection != null)
    {
        return collection.Count >= count;
    }
    var collection2 = source as ICollection;
    if (collection2 != null)
    {
        return collection2.Count >= count;
    }
    int num = 0;
    checked
    {
        using (var enumerator = source.GetEnumerator())
        {
            while (enumerator.MoveNext())
            {
                num++;
                if (num >= count)
                {
                    return true;
                }
            }
        }
    }
    // returns true for source with 0 elements and count 0
    return num == count;
}
于 2014-11-27T23:34:39.197 に答える