SelectMany
- Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence.
- Projection Operator like Select
- When we nested list, SelectMany becomes useful. We need only one loop using selectMany to traverse elements of the nested list.
- List of students and have list of subjects in it.
- Find out the subjects which Mike is enrolled to ?
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
class SoftwareStudent
{
public string Name { get; set; }
public string RollNumber { get; set; }
public List<string> Subject { get; set; }
}
static void Main(string[] args)
{
List<SoftwareStudent> students = new List<SoftwareStudent>{
new SoftwareStudent {
Name = "Anurag",
RollNumber ="1" ,
Subject= new List<string>{"Dotnet","Java","Informatica"}},
new SoftwareStudent {
Name = "Abhishek",
RollNumber ="2" ,
Subject= new List<string>{"Che","Phy"}},
new SoftwareStudent {
Name = "Mike",
RollNumber ="3" ,
Subject= new List<string>{"Dotnet","php","BigData"}}};
var result4 = students.Where(x => x.Name == "Mike").ToList();
string subjectMike=string.Empty;
foreach (var item in result4)
{
var count = item.Subject.Count;
foreach (var item1 in item.Subject)
{
subjectMike += item1 + ";";
if (--count <= 0)
{
subjectMike = subjectMike.TrimEnd(';');//Dotnet;php;BigData
}
}
}
Console.WriteLine(subjectMike);
//*******************SELECT MANY*****************//
string subjectMike1 = string.Empty;
var MikeSubSelMany = students.Where(x => x.Name == "Mike").SelectMany(student => student.Subject, (st1, subject) => new { st1.RollNumber,st1.Name, subject });
//var MikeSubSelMany1 = students.Where(x => x.Name == "Mike").SelectMany(student => student.Subject);
var count2 = MikeSubSelMany.Count();
foreach (var item2 in MikeSubSelMany)
{
subjectMike1 += item2.subject + ";";
if (--count2 <= 0)
{
subjectMike1 = subjectMike.TrimEnd(';');//Dotnet;php;BigData
}
}
Console.WriteLine(subjectMike1);
Console.ReadLine();
}
}
}
So highlighted is the use of selectmany. You only need to loop once to get the results of the subjects taken by mike.
This Piece of code also produces the same result.
Using overloaded version of SelectMany
This Piece of code also produces the same result.
Using overloaded version of SelectMany
var MikeSubSelMany = students.Where(x => x.Name == "Mike").
SelectMany(student => student.Subject);
//var MikeSubSelMany1 = students.Where(x => x.Name == "Mike").SelectMany(student => student.Subject);
var count2 = MikeSubSelMany.Count();
foreach (var item2 in MikeSubSelMany)
{
subjectMike1 += item2 + ";";
if (--count2 <= 0)
{
subjectMike1 = subjectMike.TrimEnd(';');//Dotnet;php;BigData
}
}
Console.WriteLine(subjectMike1);
Console.ReadLine();
Debugging
O/P with with both SelectMany and without Selectmany gives same result
No comments:
Post a Comment