繁体   English   中英

在 C# 中的 Linq 语句中使用 Take 时如何全部返回

[英]How Return all when Using Take in Linq statement in C#

我有一个 Take 属性,如果我传递一个我想显示的数字,例如 top (4),当 Take 为 0 时,我想全部返回,这是我的代码,当我通过 Take = 4 时返回 Top 4 但是当取为 0 我不知道如何全部归还。

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

这是请求属性:

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

您可以有条件地构建您的可查询对象。

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

您可以在 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();

只需省略“take”,toListAsync() 就会全部返回。 顺便说一句,Linqpad 是玩 Linq 结构的好工具( https://www.linqpad.net/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM