poc
poc

Reputation: 191

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

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);

Upvotes: 5

Views: 11823

Answers (3)

Aron
Aron

Reputation: 15772

Although the other users are correct in giving you the results you want...

This is NOT how you should be using Entity Framework.

This is the better way to use EF.

var query = from student in Context.Students
            where student.Id == 123
            from topic in student.Topics
            order by topic.Name
            select topic;

Notice how the structure more closely follows the logic of the business requirements.

You can almost read the code in English.

Upvotes: -1

Kosala W
Kosala W

Reputation: 2143

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

Upvotes: 7

Keith Hall
Keith Hall

Reputation: 16085

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.

Upvotes: 9

Related Questions