如果Sessions.Current.AdminProductId为null,是否可以忽略Where子句?我想将下面的代码优化为一行代码。
if (Sessions.Current.AdminProductId == null)
gvUsers.DataSource = DataAccess.Instance.Users;
else
gvUsers.DataSource = DataAccess.Instance.Users.Where(p => p.Orders.Any(o => o.ProductId == Sessions.Current.AdminProductId));
答案 0 :(得分:2)
您只需要在where子句中添加null检查,如下所示:
gvUsers.DataSource = DataAccess.Instance.Users.Where(p => (Sessions.Current.AdminProductId == null) || (Sessions.Current.AdminProductId != null && p.Orders.Any(o => o.ProductId == Sessions.Current.AdminProductId)));