Concat 2 is null

When both lists listed below in the line of code are full, my code works fine. However, the error "Value cannot be null." happens when LstNewItems is set to null. Why and how can I fix this or do I need to check if each list is null and acts accordingly?

this.radGridViewFiles.BeginInvoke((MethodInvoker)(
() => this.radGridViewFiles.DataSource = MyGlobals.ListOfItemsToControl
                                                  .Concat(MyGlobals.lstNewItems)
                                                  .ToList()
));
+5
source share
6 answers

If at all possible, never allow yourself to be in a position where the list is null, so you never need to check nulland handle this case differently. Having an empty list is nullalmost always preferable instead .

+5

MyGlobals.lstNewItems ?? Enumerable.Empty<someObjectType>()
+11

, , null:

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

:

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

+4

 ( MyGlobals.ListOfItemsToControl ?? new List<Type>()).Concat(MyGlobals.lstNewItems ?? new List<Type>()) .ToList()
+2
source

Before starting, check the null value. as,

if(MyGlobals.lstNewItems != null)
{
MyGlobals.ListOfItemsToControl.AddRange(MyGlobals.lstNewItems);
}
+1
source

If you have any number of possible zero collections to combine:

IEnumerable<T> Concat<T>(params IEnumerable<T>[] nullableCollections)
{
    return nullableCollections.Where(nc => nc != null).SelectMany(nc => nc);
}

and later you can call:

IEnumerable<T> allElements = Concat(myElements, yourElements, theirElements);

Not worrying if any of them are zero.

+1
source

Source: https://habr.com/ru/post/1524784/


All Articles