Linq返回null没有结果

时间:2015-02-24 10:53:08

标签: c# linq

在下面的简化示例中,如果没有匹配项,我想将容器设置为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 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

首先使用DefaultIfEmpty函数然后选择 例:     data.collection.Where(i =&gt; i.Type == type)                .DefaultIfEmpty(defaultObject)                。选择(i =&gt; i.Count);

答案 2 :(得分: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()

});