In SQL we have the requirement to filter the results based on a maximum or a minimum value.We use the top operator in SQL server to filter the top results based on a criteria.
We can achieve similar functionality in LINQ using the Take() and TakeWhile() extension methods.Take extension method returns the specified number of elements.TakeWhile returns the elements from a collection as long as the specified predicate returns true.
Example of Take method
We have a list of students.Each student has a RollNo and TotalMarks property.Suppose we want to display the top most students who have scored most marks.We can very easily implement this using the Take() method.
Suppose our list contains the elements as:
List<Student> lstStudents = new List<Student>(); lstStudents.Add(new Student {RollNo=1,TotalMarks=400 }); lstStudents.Add(new Student { RollNo =2, TotalMarks = 450 }); lstStudents.Add(new Student { RollNo = 3, TotalMarks = 350 }); lstStudents.Add(new Student { RollNo = 4, TotalMarks = 500 }); lstStudents.Add(new Student { RollNo = 5, TotalMarks = 650 }); lstStudents.Add(new Student { RollNo = 6, TotalMarks = 350 }); lstStudents.Add(new Student { RollNo = 7, TotalMarks = 456 }); lstStudents.Add(new Student { RollNo = 8, TotalMarks = 368 });
We can select the top 5 students who have scored most marks as:
var TopFive = (from student in lstStudents orderby student.TotalMarks select student).Take(5);
We first order the students based on the total marks .Then we select the top 5 students using the Take() method.
We display the filtered students as:
int iRank = 1; foreach (var student in TopFive) { Console.WriteLine(string.Format("Roll No={0},Rank={1}",student.RollNo,iRank)); iRank++; }
Above will print the following Student values
Roll No=3,Rank=1
Roll No=6,Rank=2
Roll No=8,Rank=3
Roll No=1,Rank=4
Roll No=2,Rank=5
Example of TakeWhile method
TakeWhile method includes the elements in the list till the predicate passed as the parameter returns true.TakeWhile method exits and does not include any more elements in the list as soon as the predicate returns false.
Suppose we want to display the list of students who have scored more than 400 TotalMarks then we can use the TakeWhile() method.
var MinimumMarks = (from student in lstStudents orderby student.TotalMarks descending select student).TakeWhile(x=>x.TotalMarks>400);
Please note that we are ordering the students based on the TotalMarks.This is required since the TakeWhile method exits as soon as the predicate returns the first false value.
Above list will contain the following Student elements
Roll No=5,TotalMarks=650
Roll No=4,TotalMarks=500
Roll No=7,TotalMarks=456
Roll No=2,TotalMarks=450
Leave a Reply