This post will discuss how to check if all items are the same in a non-empty list in C#.

1. Using Enumerable.Distinct Method

A simple solution to check if all list items have the same value is to get the distinct elements count in the list using LINQ’s Enumerable.Distinct method. If all elements in the list are the same, then the distinct count would be 1. This is demonstrated below:

Download  Run Code

 
You can also skip the first element after getting the distinct elements from a sequence and check if there are any elements left, as the following example illustrates.

Download  Run Code

2. Using Enumerable.Any Method

Another option to check if all list elements are identical is to compare each element of the list with its first element. This can be easily done using LINQ’s Enumerable.Any() method that returns true if and only if any element of a sequence satisfy a condition.

Download  Run Code

 
Alternatively, you can use the Enumerable.All method that returns true if all elements of a sequence match the conditions defined by the supplied predicate, false otherwise.

Download  Run Code

3. Using List<T>.TrueForAll Method

If you don’t prefer LINQ or do not use .NET 3.5 or above, you can use the List<T>.TrueForAll method that returns true if every element in the list satisfies the supplied predicate. Here’s an example of its usage:

Download  Run Code

That’s all about checking if all items are the same in a List in C#.