What is the difference between Select and SelectMany in Linq C#?

CsharpServer Side ProgrammingProgramming

Select operator produces one result value for every source SelectMany Operator belong to Projection Operators category. It is used to project each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence.

Example

class Demo{
   public string Name { get; set; }
   public List<string> Contents { get; set; }
   public static List<Demo>GetAllContents(){
      List<Demo> listContents = new List<Demo>{
         new Demo{
            Name = "Cap",
            Contents = new List<string> { "Nike", "Adidas" }
         },
         new Demo{
            Name = "Shoes",
            Contents = new List<string> { "Nike", "Puma", "Adidas" }
         },
      };
      return listContents;
   }
}
class Program{
   static void Main(){
      IEnumerable<List<string>> result = Demo.GetAllContents().Select(s => s.Contents);
      foreach (List<string> stringList in result){
         foreach (string str in stringList){
            Console.WriteLine(str);
         }
      }
      Console.WriteLine("---Select Many---")
      IEnumerable<string> resultSelectMany = Demo.GetAllContents().SelectMany(s => s.Contents);
      foreach (string str in resultSelectMany){
         Console.WriteLine(str);
      }
      Console.ReadKey();
   }
}

Output

Nike
Adidas
Nike
Puma
Adidas
---Select Many---
Nike
Adidas
Nike
Puma
Adidas
raja
Published on 04-Aug-2020 10:34:09
Advertisements