I have a very large object with many nullable-type variables. I also have a dictionary which I want to fill up with this object's non-null variables.
The code will look something like this
if (myObject.whatever != null) { myDictionary.Add("...",myObject.whatever); } if (myObject.somethingElse != null) { myDictionary.Add("...",myObject.somethingElse); ...
EDIT (Sorry messed up the code)
When we repeat this for the umpteenth time we get a mess of very long code. Is there some shorter way I could write this mess? I know about the Conditional Operator (aka ?) but that's just for assignments. Is there something like that for adding to a collection?
Hashtable does not allow to store null key or null value. Any attempt to store null key or value throws runtimeException (NullPointerException) in java. LinkedHashMap allows to store one null key and many null values i.e. any key can have null value in java.
Check for Not Null ElementsaddIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.
MySQL IFNULL() takes two expressions and if the first expression is not NULL, it returns the first expression. Otherwise, it returns the second expression. Depending on the context in which it is used, it returns either numeric or string value. An expression.
How about an extension method for your dictionary?
public static void AddIfNotNull<T,U>(this Dictionary<T,U> dic, T key, U value) where U : class { if (value != null) { dic.Add(key, value); } }
You could then do this:
myDictionary.AddIfNotNull("...",myObject.whatever);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With