Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to Collection if Not Null

Tags:

c#

nullable

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?

like image 726
Aabela Avatar asked Jul 26 '12 12:07

Aabela


People also ask

Which Java collection does not allow null?

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.

How do I stop adding NULL to list?

Check for Not Null ElementsaddIgnoreNull() method of CollectionUtils can be used to ensure that only non-null values are getting added to the collection.

IS NOT NULL in if condition in MySQL?

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.


1 Answers

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); 
like image 109
Botz3000 Avatar answered Oct 08 '22 18:10

Botz3000