SelectMany operator in Linq

by Sachin Singh


Posted on Thursday, 11 February 2021

Tags: SelectMany operator in Linq

How to think
How to think when working with LINQ

SelectMany Operator

we have already discussed in previous articles that like a projector machine projects slides or film on to a screen, means a projector transforms one form of things into other similarly In LINQ, projection means to take all or some properties of an object, either modify them or don't modify them and project them into a new type, same type or an anonymous type.

SelectMany Operator also belongs to the Projection Operators category which is used to project each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. Here the type (T) literally can be anything like collection of string, collection of char, collection of complex object anything like that

Let us understand this with an example. Consider the following Author class. Books property in this class is a collection of strings.

 public class Author
 {
    public string Name { get; set; }
    public string Gender { get; set; }
    public List<string> Books { get; set; }

    public static List<Author> GetAllAuthors()
    {
        List<Author> authorList = new List<Author >
        {
            new Author
            {
                Name = "Sachin",
                Gender = "Male",
               Books = new List<string> { "Book1 ", "Book2" }
            },
           new Author
            {
                Name = "Arjun",
                Gender = "Male",
               Books = new List<string> { "Book3 ", "Book4" }
            },
           new Author
            {
                Name = "Vikash",
                Gender = "Male",
               Books = new List<string> { "Book4 ", "Book5" }
            },
           new Author
            {
                Name = "Nivi",
                Gender = "Female",
               Books = new List<string> { "Book6 ", "Book7" }
            },
        };

        return authorList;
    }
 }

Example 1 : Fetch all books written by a specific Author.

Here, if we use Select operator then we will get a hierarchal result which means to print the result we will have to use two foreach blocks.


      public static void Main()
        {
           Author author =new Author();
           var BooksByVikash = author.GetAllAuthors().Where(a => a.Name == "Vikash").Select(x=>x.Books);

           foreach (var books in BooksByVikash)
           {
               foreach(var book in books)
               {
                   Console.WriteLine(book);
               }
           }
            Console.ReadLine();
        }

As you can see there is something weird in here, this is because we are selecting a collection from a collection means GetAllAuthors itself returns a collection of Authors , now you must be thinking we only want the books written by a particular Author then why we did not use Single() to just fetch one particular author , actually we can't do so because Select is an extension method on IEnumerable<T> which means we can use select operator with a collection of things only and not with a singleton result.

In short if there is a collection property and we are selecting that property from a collection of object then we will end up with an IEnumerable<List<T>> which is a collection of collection.

To solve the above problem we have SelectMany projection operator which enables us to project each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.

The above example can be rewritten with SelectMany operator as shown below.


        public static void Main()
        {
           Author author =new Author();
           var BooksByVikash = author.GetAllAuthors().Where(a => a.Name == "Vikash").SelectMany(x=>x.Books);

            foreach (var book in BooksByVikash)
               {
                   Console.WriteLine(book);
               }
                 Console.ReadLine();
         }

Notice the results are now flattened, and to print the result we just used one foreach block instead of two.

Example 2: Rewrite Example1 using SQL like syntax.

When using SQL like syntax style, we don't use SelectMany, instead we will have an additional from clause, which will get its data from the results of the first from clause.


   Authors author= new Author();
   IEnumerable<string> booksByVikash= from Author in author. GetAllAuthors ()
                                                            from Book in Author.Books
                                                            select Book;

 foreach (string Book in booksByVikash)
 {
    Console.WriteLine(Book);
 }

Output:

Output
Output