1

What is the easiest way to check multiple nullable values, to know if those that are not null are equal?

double? a = null
double? b = 2;
double? c = 3.5;

should return false

double? a = 2.5
double? b = 2;
double? c = 2;

should return false

double? a = null
double? b = 2;
double? c = 2;

should return true

double? a = 4.5;
double? b = 4.5;
double? c = 4.5;

should return true

5
  • 1
    What do you mean by "easiest"? Commented Aug 14, 2024 at 0:30
  • 7
    What if all three are null, is that a true or a false for you? Commented Aug 14, 2024 at 0:44
  • @GSerg: good question... in this case, if all three are null, that would be a true... (I think, to be honest I dont quite remember the exact case I needed this). In fact I think I had a previous if-else to check for that before calling this code... as I was only interested in the case where not all were null... Commented Sep 4, 2024 at 14:22
  • @Enigmativity: err... "less difficult"? as in "less code needed" I guess... Commented Sep 4, 2024 at 14:23
  • @patsy2k In this case you shouldn't have accepted the answer, because it will give you a false if all three are null. Commented Sep 4, 2024 at 15:41

1 Answer 1

0

This seems fairly "easy" to me:

bool NonNullsAllEqual(params double?[] inputs) =>
    inputs.Where(y => y != null).Distinct().Count() == 1;
Sign up to request clarification or add additional context in comments.

3 Comments

Easy and elegant XD. Perfect. Thanks mate
@patsy2k - It would be great if you responded to the comments on the question.
You are right, sorry. Done.

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.