0

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));
1
  • 3
    You could use .Distinct() and check the length. If it is 1, all are the same, and if it is >1, you have different values. Commented Oct 25, 2018 at 9:22

2 Answers 2

4

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();
Sign up to request clarification or add additional context in comments.

1 Comment

@SaniSinghHuttunen: even better than source or IL is documentation because if it's mentioned there it won't change in future implementations and you can rely on it: "The enumeration of source is stopped as soon as the result can be determined."
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.