gpt4 book ai didi

c# - 如何在 LINQ 中应用 if 条件?

转载 作者:太空宇宙 更新时间:2023-11-03 23:07:05 26 4
gpt4 key购买 nike

下面是我的LINQ

我想重写我的 LINQ 就好像 flagtrue 然后获取所有记录 else apply .skip( ) & take() 如此处所述

    public IEnumerable<ReportMapper> FetchReports(DateTime startDate, DateTime endDate, int docMode, int pageNumber, bool flag )
{
try
{
IEnumerable<ReportMapper> reports;
using (var entities = new DatabaseEntities1())
{
IQueryable<ReportMapper> query;
if (docMode > 0)
{
query = (from c in entities.tDocumentStatus
join d in entities.tTOCStructures on c.DocumentId equals d.DocumentID
join e in entities.tUsers on d.LastUpdatedBy equals e.UserUID
orderby c.AssignedDate descending
where c.AssignedDate >= startDate && c.AssignedDate <= endDate && c.StatusId == docMode
select new ReportMapper()
{
DocumentName = d.FolderName,
AssignedDate = c.AssignedDate,
ReviewStatus = c.tStatu.StatusName,
ActionPerformedBy = e.FirstName + " " + e.LastName
}).Skip(pageNumber * 10).Take(50);
}
else
{
query = (from c in entities.tDocumentStatus
join d in entities.tTOCStructures on c.DocumentId equals d.DocumentID
join e in entities.tUsers on d.LastUpdatedBy equals e.UserUID
orderby c.AssignedDate descending
where c.AssignedDate >= startDate && c.AssignedDate <= endDate
select new ReportMapper()
{
DocumentName = d.FolderName,
AssignedDate = c.AssignedDate,
ReviewStatus = c.tStatu.StatusName,
ActionPerformedBy = e.FirstName + " " + e.LastName
}).Skip(pageNumber * 10).Take(50);
}


reports = query.ToList<ReportMapper>();

return reports;
}
}
catch (Exception ex)
{
//handle exception
}
}

但不知道我将如何做到这一点。

注意:-请注意,上面查询中的 var docMode 用于检查是否在 where 子句中应用第三个条件(检查我的 where 子句是完全不同的)

有没有不使用 if-else 阶梯的更好方法。

最佳答案

您可以将您的查询简化为:

public IEnumerable<ReportMapper> FetchReports(DateTime startDate, DateTime endDate, int docMode, int pageNumber, bool flag)
{
using (var entities = new DatabaseEntities1())
{
IQueryable<ReportMapper> reports =
from c in entities.tDocumentStatus
join d in entities.tTOCStructures on c.DocumentId equals d.DocumentID
join e in entities.tUsers on d.LastUpdatedBy equals e.UserUID
orderby c.AssignedDate descending
where c.AssignedDate >= startDate && c.AssignedDate <= endDate
&& (docMode <= 0 || c.StatusId == docMode)
select new ReportMapper()
{
DocumentName = d.FolderName,
AssignedDate = c.AssignedDate,
ReviewStatus = c.tStatu.StatusName,
ActionPerformedBy = e.FirstName + " " + e.LastName
};

if(!flag)
reports = reports.Skip(pageNumber * 10).Take(50);

return reports.ToList();
}
}

关于c# - 如何在 LINQ 中应用 if 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40846104/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com