我有一个linq如下:
var finalist = (from b in GeneralAction.EM().Vwmembersummarydetails
where selectedPersonId.Contains(b.Id)
select new GeneralCommonFunctions.MemberDetailSumary
{
Index = 0,
ProjectText = string.Join(", ", (from d in GeneralAction.EM().Member_has_properties
join e in GeneralAction.EM().Properties on d.Property_id equals e.Id
where d.IsDeleted == 0 && d.Member_id == b.Id && e.ProjectType_id == Convert.ToInt32(projectTypeId)
select e.Project.Description).Distinct().ToArray()),
PropertyText = string.Join(", ", (from f in GeneralAction.EM().Member_has_properties
join g in GeneralAction.EM().Properties on f.Property_id equals g.Id
where f.IsDeleted == 0 && f.Member_id == b.Id && g.ProjectType_id == Convert.ToInt32(projectTypeId)
select g.LotNum).ToArray()),
PurchasePrice = GeneralCommonFunctions.GetTotalPurchasePriceByProjectType(b.Id, projectTypeId),
Name = b.Name,
Email = b.Email,
}).AsQueryable();
我想问一下,如何忽略这两个条件:
e.ProjectType_id == Convert.ToInt32(projectTypeId)
g.ProjectType_id == Convert.ToInt32(projectTypeId)
当projectTypeId为null或0时。
答案 0 :(得分:0)
要忽略这些条件,只需使用logical或:
(projectTypeId == null || Convert.ToInt32(projectTypeId) == 0 || e.ProjectType_id == Convert.ToInt32(projectTypeId))
要调用不同的函数,请使用第三个运算符。请注意,这可能不适用于Linq to SQL -
(projectTypeId == null ? GeneralCommonFunctions.GetTotalPurchasePrice(b.Id) : GeneralCommonFunctions.GetTotalPurchasePriceByProjectType(b.Id, projectTypeId))
答案 1 :(得分:0)
我是投票的人。 SO的原因是寻找真正难以找到的解决方案。但在发布之前,你似乎没有尝试过。
解决方案是用你自己的话说的 -
e.ProjectType_id == Convert.ToInt32(projectTypeId)
g.ProjectType_id == Convert.ToInt32(projectTypeId)
当projectTypeId为null或0时。
因此,将该英语句子转换为代码。
&& e.ProjectType_id == Convert.ToInt32(projectTypeId)
将成为 -
&& ((e.ProjectType_id != null && e.ProjectType_id != "0") ? e.ProjectType_id == Convert.ToInt32(projectTypeId) : true)
然后,您可以更好地优化它,如@netmage所述 -
(projectTypeId == null || Convert.ToInt32(projectTypeId) == 0 || e.ProjectType_id == Convert.ToInt32(projectTypeId))
同样地,
当projectTypeId为null时,如何调用GeneralCommonFunctions.GetTotalPurchasePrice(),当projectTypeId不为null时,调用GeneralCommonFunctions.GetTotalPurchasePriceByProjectType()。
同样变为 -
PurchasePrice = projectTypeId = null ? GeneralCommonFunctions.GetTotalPurchasePrice(...) : GeneralCommonFunctions.GetTotalPurchasePriceByProjectType(b.Id, projectTypeId),