Sunday, May 2, 2010

LINQ Samples (Projection Operators) : Select Filtered

In following example we see how to filter the using the 'where' clause. Example will produce the list of students that have roll numbers less than 10. Roll number is in int variable 'rollnum' and student's name are in string variable 'Studname'.

See how first we need to fetch the element and the corresponding positions such that we can fetch the proper name from studname'



private void SelectFiltered()
{
int[] Rollnum = { 6, 8, 2, 4, 12, 11, 7, 1, };
string[] StudName = { "Betty", "Helen", "Alice", "Ben", "Zen", "Jim", "Davan", "Alan" };

var roll = Rollnum
// get the Element,index
.Select( (a,b) => new
{
rollnum = a ,
index = b
})
// get the Rollnum which are < 10
.Where((a) => a.rollnum < 10)
// get the studname corresponding to the Rollnum index
.Select((a)=> new
{
stud = StudName[a.index]
})
//Order based on name
.OrderBy(c=>c.stud);

Console.WriteLine("Student with Roll num < 10");
foreach (var s in roll)
{
Console.WriteLine("{0}", s.stud);
}
}


OUTPUT

Student with Roll num < 10
Alan
Alice
Ben
Betty
Davan
Helen

No comments:

Post a Comment