【发布时间】:2015-10-13 14:03:35
【问题描述】:
任何人都可以在此 linq 语句的 where 中看到三元组有什么问题吗:
var organizations = Context.Set<Domain.Content.Organisation>()
.Where(x => x.ShowCompanyPage == (showCompanyPagesOnly ? true : x.ShowCompanyPage))
如果 showCompanyPagesOnly 设置为 true,我会得到 4 个结果,这是正确的,只有四个公司的 ShowCompanyPage = true。
但是,如果我将其设置为 false,我预计会有 1000 多个结果(所有公司)。但我仍然只得到 4 个。
我的逻辑是不是:
if showCompanyPagesOnly is true, then give me results where x.ShowCompanyPage == true
else give me results where x.ShowCompanyPage = whatever is in the column (ie ALL Organisations)
?
x.ShowCompanyPage 是一个可为空的 bool 列。
完整代码:
public Result<IList<Organisation>> GetAllOrganisations(bool showCompanyPagesOnly = false)
{
var result = new Result<IList<Organisation>>();
try
{
var organizations = Context.Set<Domain.Content.Organisation>()
.Where(x => x.ShowCompanyPage == (showCompanyPagesOnly == true ? true : x.ShowCompanyPage)) // show only company pages or show all
.AsNoTracking()
.Select(x => new DataContracts.Content.Organisation
{
Id = x.Id,
Name = x.Name,
OrganisationTypeId = x.OrganisationTypeId,
IsCustomer = x.IsCustomer,
SeoName = x.SeoName,
Description = x.Description,
Website = x.Website
}).OrderBy(x => x.Name).ToList();
result.Data = organizations;
}
catch (Exception ex)
{
result.SetException(ex);
HandleError(ex);
}
return result;
}
【问题讨论】:
-
似乎毫无意义,因为 x.ShowCompanyPage == x.ShowCompanyPage 将始终为真,所以您真正拥有的是 x.ShowCompanyPage == showCompanyPagesOnly
-
@MikeT 我不认为你是正确的,如果 showCompanyPagesOnly 我想一次显示所有。列中的值可以是 true、false 或 null。但是您的建议一次限制为一个值。
-
错过阅读你真正拥有的是(showCompanyPagesOnly ? true : true )
-
如果 showCompanyPagesOnly 为真,我会检查我是否在关注您想要的内容,您想要 ShowCompanyPage = true 的记录,否则您想要所有内容?
-
@MikeT - 正是 - 这就是我想要的逻辑。有什么想法吗?
标签: c# linq where-clause ternary-operator