Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concat 2 lists when one is null

When both lists below on the line of code are populated my code works fine. However the error "Value cannot be null." occurs when LstNewItems is set to null. Why and how can i fix this or do i have to check if each list is null beforehand and act accordingly ?

this.radGridViewFiles.BeginInvoke((MethodInvoker)(
() => this.radGridViewFiles.DataSource = MyGlobals.ListOfItemsToControl
                                                  .Concat(MyGlobals.lstNewItems)
                                                  .ToList()
));
like image 786
user1438082 Avatar asked Jan 31 '14 21:01

user1438082


3 Answers

You can use

MyGlobals.lstNewItems ?? Enumerable.Empty<someObjectType>()
like image 72
Rudis Avatar answered Oct 26 '22 22:10

Rudis


If at all possible, never let yourself be in the position where a list is null, so that you never need to check for null and handle that case any differently. Having an empty list instead of null is virtually always preferable.

like image 24
Servy Avatar answered Oct 26 '22 23:10

Servy


What I do is create an extension method that can create an empty list if the enumeration is null:

public static IEnumerable<T> NeverNull<T>(this IEnumerable<T> value)
{
   return value ?? Enumerable.Empty<T>();
}

Then you can do:

this.radGridViewFiles.BeginInvoke((MethodInvoker)(
() => this.radGridViewFiles.DataSource = MyGlobals.ListOfItemsToControl
                                                  .Concat(MyGlobals.lstNewItems.NeverNull())
                                                  .ToList()
));

Example

like image 29
Mike Christensen Avatar answered Oct 27 '22 00:10

Mike Christensen