Reputation: 4300
I have an extensions array and I have to find out whether all the elements in the array has the same value or different values using lambda expressions. I have written the below code and its always returning me true. In the following extensions array, it should return me false as the .bmp is different extensions than others. Could you help me to achieve the task?
string[] extensions = { ".doc", ".doc", ".bmp" };
var result = extensions.All(x => extensions.Contains(x));
Upvotes: 0
Views: 1584
Reputation: 18084
Case-sensitive comparison:
string[] extensions = { ".doc", ".doc", ".bmp" };
bool hasSameExtensions = extensions.Distinct().Count() == 1;
Case-insensitive comparison:
string[] extensions = { ".doc", ".doc", ".DOC" };
bool hasSameExtensions = extensions.Distinct(StringComparer.OrdinalIgnoreCase).Count() == 1;
Upvotes: 0
Reputation: 460208
You are checking if all items in an array are contained in this array, which is of course true.
You want:
string firstExt = extensions.First();
var allSame = extensions.Skip(1).All(x => firstExt == x); // use String.Equals(s1,s2,StringComparison.InvariantCultureIgnoreCase) if you want to compare in a case insensitive manner
Other way using Distinct
(not more efficient):
var allSame = !extensions.Distinct().Skip(1).Any();
Upvotes: 4