2015-02-24 120 views
0

在下面的簡化示例中,如果不存在任何匹配,我想將Containers設置爲nullLinq沒有結果返回null

_viewModel.Materials = _jobMaterials.Select(x=> new { 

    //Containers that the material my be in 
    Containers = (materialContainers.Where(mcl => mcl.Field<string>("MATKey") == x.Field<string>("MATKey")).Any()) ? 
        materialContainers.Where(mcl => mcl.Field<string>("MATKey") == x.Field<string>("MATKey")).Select(mcl => new 
        { 
         Id = mcl.Field<int>("SERIDNumber"), 
         Description = mcl.Field<string>("SERDescription").Trim(), 
         Volume = mcl.Field<int>("SERVolume"), 
         ContractedStatus = mcl.Field<int>("Contracted"), 
         OnJob = Convert.ToBoolean(mcl.Field<int>("OnJob")) 
        }) : null 

}); 

上面的作品,但是有沒有更簡潔的方法?就像DefaultIfEmptyFirstOrDefault的組合一樣。

無論工作在隔離,FirstOrDefault返回時有多個匹配,而DefaultIfEmpty返回包含null集合,如果沒有匹配的單個項目。

+3

沒有內置。定義你自己的幫手方法。現在查詢代碼非常冗餘且不可讀。 – usr 2015-02-24 10:57:10

+0

同意,因此查詢;)謝謝,是有道理的 – SWa 2015-02-24 11:06:19

回答

0

增加了一個輔助方法

public static IEnumerable<object> NullIfEmpty(this IEnumerable<object> item) 
{ 
     return item.Any() ? item : null; 
} 

用法:

_viewModel.Materials = _jobMaterials.Select(material => new { 

    //Containers that the material my be in 
    Containers = materialContainers.Where(mcl => mcl.Field<string>("MATKey") == material.Field<string>("MATKey")) 
       .Select(mcl => new { 
          Id = mcl.Field<int>("SERIDNumber"), 
          Description = mcl.Field<string>("SERDescription").Trim(), 
          Volume = mcl.Field<int>("SERVolume"), 
          ContractedStatus = mcl.Field<int>("Contracted"), 
          OnJob = Convert.ToBoolean(mcl.Field<int>("OnJob")) 
         }) 
       .NullIfEmpty() 

}); 
1

嘗試此代碼:

_viewModel.Materials = _jobMaterials 
.Select(x=>materialContainers.Where(mcl => mcl.Field<string>("MATKey") == x.Field<string>("MATKey"))) 
.Select(m => new { 
     //Containers that the material my be in 
     Containers = m.Any() ? 
        m.Select(mcl => new 
        { 
         Id = mcl.Field<int>("SERIDNumber"), 
         Description = mcl.Field<string>("SERDescription").Trim(), 
         Volume = mcl.Field<int>("SERVolume"), 
         ContractedStatus = mcl.Field<int>("Contracted"), 
         OnJob = Convert.ToBoolean(mcl.Field<int>("OnJob")) 
        }) : null 
0

使用DefaultIfEmpty功能第一然後選擇 例如: data.collection.Where(ⅰ=> i.Type ==型) .DefaultIfEmpty(defaultObject) 。選擇(i => i.Count);