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 int AuthorId; public Book(int id,string name,int authorId) { Id = id; Name = name; AuthorId = authorId; } } |
We can create a join with the SelectMany operator to see books’ name with authors . Consider the following query:
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 30 31 32 | //create sample data IEnumerable<Author> authors = new List<Author>() { new Author(1,"Stephen", "King"), new Author(2,"James", "Patterson"), new Author(3,"Mark", "Twain") }; IEnumerable<Book> books = new List<Book>() { new Book(1,"It",1), new Book(2,"The Shining",1), new Book(3,"Murder Games",2), new Book(4,"The Innocents Abroad",3), new Book(5,"Huckleberry Finn",3), new Book(6,"The Adventures of Tom Sawyer",3) }; //Linq query var authorBooks = authors .SelectMany(a => books.Where(b => b.AuthorId == a.Id) .Select(b => new { Name = b.Name, AuthorName = string.Concat(a.Name, " ", a.LastName) })); foreach (var item in authorBooks) { Console.Write(" Author :{0} \n Book : Name:{1} \n\n", item.AuthorName,item.Name); } Console.ReadLine(); |