All() and TrueForAll() are same in C#?

Kundan Zalte
.Net Programming
Published in
2 min readJan 16, 2024

While working on one of the feature I stumbled upon a thought whether I should use All() or TrueForAll() ? are they same? if they are same then why we have two different methods?

You must be having these questions right?

I did some research around it and I’ll be sharing those details with you in this blog!

Usage -

  • All() and TrueForAll() both methods use for iteration on a collection of item to determine if it satifies the given condition for all the elements.
  • All() and TrueForAll() both methods returns True if given condition is satisfied or else False.

Where Should we use All() -

  • All() is a LINQ extension method that is used on collections i.e. IEnumerable<T>.
  • It is preferred due to its large scope and applicability since it is part of Linq.
  • It is slower in execution as compare to TrueForAll().
  • Example -
int[] numberArray = {1,2,3,4,5,6};
List<int> numberList = new List<int>{ 1, 2, 3, 4, 5, 6 };

// With All()
// Checking if all elements are positive
var arrayResult = numberArray.All(x => x > 0);
Console.WriteLine(arrayResult); // True

Where Should we use TrueForAll() -

  • TrueForAll() is not part of Linq but it is available on class List<T>
  • It is less know in developers since it is a legacy method.
  • It is faster in execution compare to All().
  • Example -
int[] numberArray = {1,2,3,4,5,6};
List<int> numberList = new List<int>{ 1, 2, 3, 4, 5, 6 };

// With TrueForAll()
// Checking if all elements are positive
var listResult = numberList.TrueForAll(x => x > 0);
Console.WriteLine(listResult); // True

Conclusion -

When working with LINQ to query collections, the most common choice for checking if all elements meet a condition is the All() method. This method works with a variety of collection types. However, if you're exclusively working with List<T> collections and need to perform the same check, you have the option of using TrueForAll(). Just remember that TrueForAll() is exclusive to List<T> and won't work with other collection types.

--

--

Kundan Zalte
.Net Programming

Software Engineer @MasterCard | Angular , React , .Net, Oracle, Cybersecurity