How to Compare Values in Array

.net, arrays, c#, c#-2.0

Solution

This can be done nicely using lambda expressions.

For an array, named `arr`:

var allSame = Array.TrueForAll(arr, x => x == arr[0]);

For an list (`List<T>`), named `lst`:

var allSame = lst.TrueForAll(x => x == lst[0]);

And for an iterable (`IEnumerable<T>`), named `col`:

var first = col.First();
var allSame = col.All(x => x == first);

Note that these methods don't handle empty arrays/lists/iterables however. Such support would be trivial to add however.

Problem

If you have a string of "1,2,3,1,5,7" you can put this in an array or hash table or whatever is deemed best. How do you determine that all value are the same? In the above example it would fail but if you had "1,1,1" that would be true.

Original source