Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting first non null value in a model

Tags:

c#

Let's say I have a model class that looks like this:

   public class ModelTest {
        public string val1 {get;set;}
        public string val2 {get;set;}
        public string val3 {get;set;}
   }

Somewhere in my code this ModelTest gets its data. The caveat is that, only 1 of them will hold a value

   var model = new ModelTest() {val1=null, val2="value", val3=null} //Sudo code 

What I am trying to do somehow, is compare a value to whichever 1 of the 3 items can potentially have a values, so something like:

     var testCompare = "someValue"

     if (testCompare == model. ....//how can I get the NOT NULL value from ModelTest here for comparison
like image 976
Shrimp2022 Avatar asked May 31 '26 15:05

Shrimp2022


2 Answers

While your data model isn't ideal, it is possible to check each of the properties by utilizing the || operator to compare each value. As long as your testCompare variable does not contain null, you can also omit a null check.

if (model.val1 == testCompare || 
    model.val2 == testCompare || 
    model.val3 == testCompare)
{ }

As mentioned in the comments, if you want a more succinct version, you can use the null coalescing operator, ??, to check subsequent properties if your prior property returns null. At the end of the null coalescing chain, the first non-null property will be compared to your testCompare string. Note that you must wrap all three properties in parentheses and that this has different behavior; it only tests the first non-null property whereas the previous version tests ALL properties for a match.

if (testCompare == (model.val1 ?? model.val2 ?? model.val3))
{
}
like image 158
David L Avatar answered Jun 03 '26 03:06

David L


You could add a property to your ModelTest class that provides the first non-null value (if any) in your object:

public class ModelTest
{
    public string val1 { get; set; }
    public string val2 { get; set; }
    public string val3 { get; set; }

    public string val => val1 ?? val2 ?? val3;
}

and then check against that:

if (model.val == testCompare) { }
like image 40
Astrid E. Avatar answered Jun 03 '26 04:06

Astrid E.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!