如果查询为空而没有检查大小,则Linq并选择默认值

时间:2014-09-23 15:11:17

标签: c# .net linq

而不是检查原始查询是否有任何项目,这可以简化吗?我讨厌做这种类型的检查,并在这种类型的检查后分配一个默认值。

顺便说一下,这是一个实体框架查询,所以它需要成为整个查询的一部分。

LogoId = (from t in a.Event.Assets
          where t.Type == EventAssetType.Logo
          select t.AssetId).Any() ? (from t in a.Event.Assets
                                     where t.Type == EventAssetType.Logo
                                     select t.AssetId).FirstOrDefault() : (a.Event.Organization != null && a.Event.Organization.OrganizationAsset != null ? a.Event.Organization.OrganizationAsset.AssetId : 0),

3 个答案:

答案 0 :(得分:5)

DefaultIfEmpty有一个带参数的重载。

LogoId = (from t in a.Event.Assets
      where t.Type == EventAssetType.Logo
      select t.AssetId)
.DefaultIfEmpty((a.Event.Organization != null && a.Event.Organization.OrganizationAsset != null ? a.Event.Organization.OrganizationAsset.AssetId : 0)).First();

答案 1 :(得分:4)

我相信你能做的更简单就是

LogoId = from t in a.Event.Assets
         where t.Type == EventAssetType.Logo
         select t.AssetId).FirstOrDefault();

if (LogoId == 0) 
{
    LogoId = a.Event.Organization != null && a.Event.Organization.OrganizationAsset != null 
        ? a.Event.Organization.OrganizationAsset.AssetId : 0;
}

不确定您的代码是否更简单,但可能更具可读性。

答案 2 :(得分:2)

使用??运算符:

(from t in a.Event.Assets
          where t.Type == EventAssetType.Logo
          select new Nullable<int>(t.AssetId)).FirstOrDefault() ??  (a.Event.Organization != null && a.Event.Organization.OrganizationAsset != null ? a.Event.Organization.OrganizationAsset.AssetId : 0)