LINQ to SQL. how to select all records 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 that works fine.

this shows the top 5 records (sorted by their count) if I pass the number OfRecords = 5.

Now my problem is that I do not want to modify the request. so what should I do in this query to show all entries. This is due to my requirement, I want to use the same query to show all the refrigerators and Top 5, top 10 refrigerators.

I am not sure if LINQ can be used. but I think there must be something related to this.

+4
source share
5 answers

, , . if .

if(allRecordRequired)
{
  numberOfRecords = 2000000;
}

.

+2

Take , , .

, :

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

:

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

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

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

numberOfRecords a int?, null, Take(numberOfRecords)

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

if(numberOfRecords.HasValue)
    result = result.Take(numberOfRecords.Value);

return result.ToList();

, , , , numberOfRecords , , .

+4

. , ( ) , . .

+1

, , , (, - 2 , ):

, linq 2 sql. :

public static class LinqExtensions
{
    public static IEnumerable<TResult> TakeIfNotNull<TResult>(this IEnumerable<TResult> source, int? count)
    {
        return !count.HasValue ? source : source.Take(count.Value);
    } 
}

int? int -, count null Take -.

, , :

.OrderByDescending(k => k.Count).TakeIfNotNull(numberOfRecords).ToList();

numberOfCounts null, .

+1

Source: https://habr.com/ru/post/1546960/


All Articles