Below is some linqpad test code. When this runs it errors because the second instance of "item" has a null list of subitems as opposed to an empty list.
I want to treat 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 initialising an empty list when there's a null.
in other words, I could do this:
from si in (i.subitems == null ? new List<item>() : i.subitems)
but that's a little ugly and I wondered how I could improve on that?
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 a lambda and treat nulls the same way?
Cheers, Chris
isEmpty() method of CollectionUtils can be used to check if a list is empty without worrying about null list. So null check is not required to be placed everywhere before checking the size of the list.
LINQ to SQL does not impose C# null or Visual Basic nothing comparison semantics on SQL. Comparison operators are syntactically translated to their SQL equivalents. The semantics reflect SQL semantics as defined by server or connection settings.
It will return an empty enumerable. It won't be null.
Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.
You could use the null coalescing operator
var res = (from i in myItemList
from si in i.subitems ?? new List<item>()
select new { i.itemname, subitemname = si.itemname }).ToList();
But I think you should just filter the empty ones out
var res = (from i in myItemList
where i.subitems != null
from si in i.subitems
select new { i.itemname, subitemname = si.itemname }).ToList();
As for a lambda version you could say
var res = myItemList.Where(x => x.subitems != null)
.SelectMany(
x => x.subitems.Select(
y => new { x.itemname, subitemname = y.itemname }
)
);
But the query syntax version is way more readble.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With