Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL . how to select all record using .take()

var result=(from refridgerators in context.A                                               
                                     group refridgerators by new { refridgerators.Id, refridgerators.Name } into gr
                                     select new DAO<String>
                                     {
                                         Key = gr.Key.Name,
                                         Count = gr.Count()
                                     }).OrderByDescending(k => k.Count).Take(numberOfRecords).ToList();

This is my linq to sql query this is working perfectly fine.

this shows top 5 records (sorted by their count) if i pass numberOfRecords =5.

now my problem is i don`t want to modify query. so what should i do in above query to show all records. This is in relation with my requirement i want to use same query to show all refridgerators and Top 5 , top 10 refridgerators.

I am not sure if it is possible using LINQ. but i guess there must be something related to this.

like image 210
Learner Avatar asked Jul 03 '14 07:07

Learner


1 Answers

I would simply don't add the Take to the query but to the code where you consume this query.

So for example:

public static IEnumerable<DAO> GetRefrigerators()
{
    var query = from refridgerators in context.A                                               
                group refridgerators by new { refridgerators.Id, refridgerators.Name } into gr
                select new DAO<String>
                {
                     Key = gr.Key.Name,
                     Count = gr.Count()
                };
    return query.OrderByDescending(k => k.Count);
}

Now you can either use:

var refrigerators = GetRefrigerators().Take(5).ToList();

or

var refrigerators = GetRefrigerators().Take(10).ToList();

or

var refrigerators = GetRefrigerators().ToList();
like image 125
Tim Schmelter Avatar answered Oct 02 '22 00:10

Tim Schmelter