I have this class:
class OriginalClass {
string FirstItem;
List<string> ListOfSecondItems;
}
I want to convert the list of one class into the list of another, or to “flatten” this class into new one:
class FlattenedClass {
string First;
string Second;
}
I’m using 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 if list of second items is empty I lose the first item. I want to have some “(default)” value to be used if the list is null or empty. I guess DefaultIfEmpty is the key, but don’t know how to incorporate it into existing query.
This call to
DefaultIfEmptysays: “If that ListOfSecondItems is empty, use a single null instead.”Your question mentions the possibility that ListOfSecondItems might be null. This code handles that possibility. It also supplies a default string instead of null (using the other version of DefaultIfEmpty).