How Return all when Using Take in Linq statement in C#

Viewed 73

I have a Take property that if I pass a number I want to show for example top (4) and when the Take is 0 I want to return all, this is my code that is returning Top 4 when I pass Take = 4 but when Take is 0 I dont know how to return all.

  var Notes = await zigzyDbContext.RealEstateAgentNotes
            .Include(i => i.RealEstateAgent)
            .Where(w => w.RealEstateAgent.Guid == request.RealEstateAgentGuid)
            .Join(zigzyDbContext.SupportUsers,
                j => j.CreatedById,
                j => j.Id,
                (j, k) => new
                {
                    RealEstateAgentNote = j,
                    Support = k
                })
            .Where(w => w.Support != null)
            .OrderByDescending(o => o.RealEstateAgentNote.CreatedDate)
            .Take(request.Take)
            .ToListAsync();

and this is the request property:

            public Guid RealEstateAgentGuid { get; set; }
            public int Take { get; set; }
3 Answers

You can build your queryable conditionally.

var query = zigzyDbContext.RealEstateAgentNotes
            .Include(i => i.RealEstateAgent)
              .Where(w => w.RealEstateAgent.Guid == request.RealEstateAgentGuid)
            .Join(zigzyDbContext.SupportUsers,
                j => j.CreatedById,
                j => j.Id,
                (j, k) => new
                {
                    RealEstateAgentNote = j,
                    Support = k
                })
            .Where(w => w.Support != null)
            .OrderByDescending(o => o.RealEstateAgentNote.CreatedDate);

if (request.Take > 0)
{
    query = query.Take(request.Take)
}

var notes = await query.ToListAsync();

You can add the ternary operator inside the Take function

 var Notes = await zigzyDbContext.RealEstateAgentNotes
            .Include(i => i.RealEstateAgent)
            .Where(w => w.RealEstateAgent.Guid == request.RealEstateAgentGuid)
            .Join(zigzyDbContext.SupportUsers,
                j => j.CreatedById,
                j => j.Id,
                (j, k) => new
                {
                    RealEstateAgentNote = j,
                    Support = k
                })
            .Where(w => w.Support != null)
            .OrderByDescending(o => o.RealEstateAgentNote.CreatedDate)
            .Take(request.Take > 0 ? request.Take:Int32.MaxValue)
            .ToListAsync();

Just leave out "take" and the toListAsync() will return all. Btw, Linqpad is a great tool for playing with Linq constructs (https://www.linqpad.net/)

Related