Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to take 100 records from linq query based on a condition

Tags:

c#

linq

I have a query, which will give the result set . based on a condition I want to take the 100 records. that means . I have a variable x, if the value of x is 100 then I have to do .take(100) else I need to get the complete records.

var abc=(from st in Context.STopics 
where  st.IsActive==true && st.StudentID == 123 
select new result()
{
 name = st.name }).ToList().Take(100);
like image 588
poc Avatar asked Mar 22 '16 07:03

poc


2 Answers

Because LINQ returns an IQueryable which has deferred execution, you can create your query, then restrict it to the first 100 records if your condition is true and then get the results. That way, if your condition is false, you will get all results.

var abc = (from st in Context.STopics 
where st.IsActive && st.StudentID == 123 
select new result
{
 name = st.name
});
if (x == 100)
  abc = abc.Take(100);
abc = abc.ToList();

Note that it is important to do the Take before the ToList, otherwise, it would retrieve all the records, and then only keep the first 100 - it is much more efficient to get only the records you need, especially if it is a query on a database table that could contain hundreds of thousands of rows.

like image 130
Keith Hall Avatar answered Sep 24 '22 20:09

Keith Hall


One of the most important concept in SQL TOP command is order by. You should not use TOP without order by because it may return different results at different situations.

The same concept is applicable to linq too.

 var results = Context.STopics.Where(st => st.IsActive && st.StudentID == 123)
              .Select(st => new result(){name = st.name})
              .OrderBy(r => r.name)                 
              .Take(100).ToList();

Take and Skip operations are well defined only against ordered sets. More info

like image 31
Kosala W Avatar answered Sep 22 '22 20:09

Kosala W