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