The SelectMany operator creates a one-to-many output projection sequence over an input sequence. SelectMany will return 0 or more output elements for every input element.
We’ll need some classses which have some properies. In the posts on LINQ we take the following collections for tutorial
Create the following classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Author { public int Id; public string Name; public string LastName; public Author(int id, string name, string lastName) { Id = id; Name = name; LastName = lastName; } } public class Book { public int Id; public string Name; public Author Author; public Book(int id, string name, Author author) { Id = id; Name = name; Author = author; } } |
Create example data for queries:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//create sample data List<Author> authors = new List<Author>() { new Author(1,"Stephen", "King"), new Author(2,"James", "Patterson"), new Author(3,"Mark", "Twain") }; List<Book> books = new List<Book>() { new Book(1,"It",authors[0]), new Book(2,"The Shining",authors[0]), new Book(3,"Murder Games",authors[1]), new Book(4,"The Innocents Abroad",authors[2]), new Book(5,"Huckleberry Finn",authors[2]), new Book(6,"The Adventures of Tom Sawyer",authors[2]) }; |
Example 1: Lets look this example, we can simply select details of author from books. Because “Book class” has Author property
1 2 3 4 5 6 7 |
IEnumerable<Author> authorsfromBooks = books.Select(x=>x.Author); foreach (var item in authorsfromBooks) { Console.WriteLine(item.Name); } |
Example 2: But we can’t select directly book’s name from author. Therefore we must use multiple tables with where clause.
Linq provides SelectMany Method that the SelectMany operator creates a one-to-many output projection sequence over an input sequence.
1 2 3 4 5 6 7 |
IEnumerable<Book> booksfromAuthors = authors.SelectMany(x=>books.Where( b=> b.Author == x)); foreach (var item in booksfromAuthors) { Console.WriteLine(item.Name); } |
Example 4: Select books with details(Author’s name and lastname)
1 2 3 4 5 6 7 8 9 |
var booksDetail = authors.SelectMany(a => books.Where(b => b.Author == a) .Select(b => new { BookDetail = string.Concat(b.Name," -(",a.Name," ",a.LastName,")") })); foreach (var item in booksDetail) { Console.WriteLine(item.BookDetail); } |