LoginSignup
5
1

More than 3 years have passed since last update.

LINQ All() の挙動について

Last updated at Posted at 2020-06-29

LINQにはラムダで条件式を渡し、要素全てがその条件を満たしているかを判定してboolを返す、
All()という便利なメソッドがあります。

List<int> list1 = new List<int> { 1, 2, 3 };

if (list1.All(n => n > 0)) // ← 要素が全て0より大きいのでtrue
{
    Console.WriteLine("正の整数です");
}

// 出力: 正の整数です

空のリストに対してこのメソッドを実行すると、直感とは異なる挙動になります。
(「全てが満たす」だからfalseになると思っていた)

List<int> list2 = new List<int>();

if (list2.All(n => n > 0)) // ← true
{
    Console.WriteLine("正の整数です");
}

// 出力: 正の整数です

All()の実装を見てみると、リストの要素が空の場合は必ずtrueが返るようになっていました。
Any()等を組み合わせて判定するのが安全そうです。

// https://github.com/microsoft/referencesource/blob/master/System.Core/System/Linq/Enumerable.cs#L1305

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
    if (source == null) throw Error.ArgumentNull("source");
    if (predicate == null) throw Error.ArgumentNull("predicate");
    foreach (TSource element in source) { // ← sourceの要素が0なのでループが回らない
        if (!predicate(element)) return false;
    }
    return true; // ← ので、必ずtrueが返る
}
List<int> list2 = new List<int>();

if (list2.Any() && list2.All(n => n > 0)) // ← false
{
    Console.WriteLine("正の整数です");
}
5
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1