Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between Select and SelectMany in Linq C#?
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
Advertisements