Select and SelectMany in LINQ

Sunday, 26 November 2017

Select and SelectMany in LINQ


SelectMany: Flattens collections into a single collection (similar to cross join in SQL). It return lists of lists into a single list.

Select: gets a list of lists. So we have to use two nested foreach loops to print the subjects.


// With Select
IEnumerable<IEnumerable<Author>> tmp1 = SampleData.Books.Select(book => book.Authors);
tmp1.Dump("With Select");
foreach (var authors in tmp1)
{
  foreach (var author in authors)
  {
    author.LastName.Dump();
  }
}

// With SelectMany
IEnumerable<Author> tmp2 = SampleData.Books.SelectMany(book => book.Authors);
tmp2.Dump("With SelectMany");
foreach (var author in tmp2)
{
  author.LastName.Dump();
}

var bookAuthors =
  from book in SampleData.Books
  from author in book.Authors
  select author.LastName;

bookAuthors.Dump("With a double from");

No comments:

Post a Comment