Dialecticus
Dialecticus

Reputation: 16761

How to use DefaultIfEmpty in nested query

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.

Upvotes: 4

Views: 363

Answers (1)

Amy B
Amy B

Reputation: 110071

This call to DefaultIfEmpty says: "If that 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 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).

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); 

Upvotes: 3

Related Questions