Bassam Alugili
Bassam Alugili

Reputation: 17033

All is executed, although the list is empty

namespace ConsoleApplication15
{
  using System;
  using System.Collections.Generic;
  using System.Linq;

  public class Test
  {
    public string Status { get; set; }
  }

  public static class Program
  {
    static void Main(string[] args)
    {
      var list = new List<Test>();

      if (list.Any(x => x.Status == "Tester"))
      {
        Console.WriteLine("This Line will not execute");
      }

      if (list.All(x => x.Status == "Tester"))
      {
        Console.WriteLine("This line will execute");
      }
    }
  }
}

Can anyone explain to my please why the line All condiation is executed and the Any not? All--> The list does not contains items!

Upvotes: 2

Views: 82

Answers (4)

Habib
Habib

Reputation: 223352

Enumerable.All would return true if the the source sequence (in your case a list) is empty.

This is documented for Enumerable.All

Return Value: true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

Upvotes: 3

catfood
catfood

Reputation: 4331

.All() executes because it's literally true that every item in the list meets the condition. There are zero items in the list, and zero items meet the condition. That's all of them.

.Any() doesn't execute because the number of matching items is zero. Any has to be more than zero.

Think of it this way: Every time I eat a giraffe, All the time, I get indigestion. But I have never actually eaten a giraffe. It has not happened Any times.

Upvotes: 3

cat916
cat916

Reputation: 1361

true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

Base on the MSDN statement, you got the result is True . Enumerable.All() Method MSDN

Upvotes: 4

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101701

If you look at the implementation of All method:

public static bool All<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
    foreach (TSource element in source) 
    {
       if (!predicate(element)) return false;
    }
    return true;
}

You can see that it tries to iterate over the elements.But since there is no element in the source sequence, it's immediately return true.On the other hand the Any method:

public static bool Any<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) 
{
    foreach (TSource element in source) 
    {
       if (predicate(element)) return true;
    }
    return false;
}

Does the same thing but it immediately return false.

Upvotes: 3

Related Questions