How to handle null lists, like empty lists in linq?

Below is the linqpad validation code. When this causes errors, because the second instance of "item" has a null list of subitems, not an empty list.

I want to handle both situations (null or empty list) in exactly the same way, but I wondered if there was a cleaner way than just putting a null check on the list and initializing the empty list when there is zero.

In other words, I could do this:

from si in (i.subitems == null ? new List<item>() : i.subitems)

but it's a little ugly, and I thought, how can I improve this?

public class item
{
    public string itemname { get; set; }
    public List<item> subitems { get; set; }
}

void Main()
{
    List<item> myItemList = new List<item>() 
    {
        new item 
        {
            itemname = "item1",
            subitems = new List<item>()
            {
                new item { itemname = "subitem1" },
                new item { itemname = "subitem2" }
            }
        },
        new item 
        {
            itemname = "item2"
        }
    };

    myItemList.Dump();

    var res = (from i in myItemList
            from si in i.subitems
            select new {i.itemname, subitemname = si.itemname}).ToList();

    res.Dump();
}

as a bonus question, can this same linq query be represented as lambda and treat zeros in the same way?

Cheers Chris

+5
4

null coalescing

var res = (from i in myItemList
           from si in i.subitems ?? new List<item>()
           select new { i.itemname, subitemname = si.itemname }).ToList();

,

var res = (from i in myItemList
           where i.subitems != null
           from si in i.subitems
           select new { i.itemname, subitemname = si.itemname }).ToList();

-,

var res = myItemList.Where(x => x.subitems != null)
                    .SelectMany(
                        x => x.subitems.Select(
                            y => new { x.itemname, subitemname = y.itemname }
                        )
                     );

.

+13
from si in (i.subitems ?? new List<item>())

?

+11

() , .

public static IEnumerable<T> EnsureNotEmpty<T>(this IEnumerable<T> enumerable) {
  if ( enumerable == null ) {
    return Enumerable.Empty<T>();
  } else { 
    return enumerable;
  }
}
+8

, . , , null .

, , , .

The zero coalescing operator is what you are looking for, as Hunter Daily pointed out

0
source

All Articles