How to use DefaultIfEmpty in a subquery

I have this class:

class OriginalClass { string FirstItem; List<string> ListOfSecondItems; } 

I want to convert a list of one class to a list of another, or "smooth" this class into a new one:

 class FlattenedClass { string First; string Second; } 

I use this LINQ expression to convert from one to another:

 OriginalClass original; var flattened = from Item in original from secondItem in item.ListOfSecondItems select new FlattenedClass(item.FirstItem, secondItem); 

The problem is that the list of all elements is empty. I am losing the first element. I want to have a value of "(default)" which will be used if the list is empty or empty. I think DefaultIfEmpty is the key, but does not know how to include it in an existing request.

+4
source share
1 answer

This call to DefaultIfEmpty says: "If this ListOfSecondItems is empty, use a single null instead."

 var flattened = from Item in original from secondItem in item.ListOfSecondItems.DefaultIfEmpty() select new FlattenedClass(item.FirstItem, secondItem); 

Your question mentions that ListOfSecondItems can be null. This code handles this feature. It also supplies the default string instead of zero (using a different version of DefaultIfEmpty).

 var flattened = from Item in original let subList = item.ListOfSecondItems ?? new List<string>() from secondItem in subList.DefaultIfEmpty("(default)") select new FlattenedClass(item.FirstItem, secondItem); 
+3
source

All Articles