Simant
Simant

Reputation: 4300

Check if a string array has same string value or not using Lambda Expression

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

Answers (2)

Rui Jarimba
Rui Jarimba

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

Tim Schmelter
Tim Schmelter

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

Related Questions