创建null而不是空字典,其中IEnumerable没有数据

时间:2015-06-03 06:44:00

标签: c# linq

以下是我的Linq代码,在这里我们返回Dictionary<string,string>,同时为每个字符串键填充对象值,我们在内部填充FieldPropertyMapping,在下面的代码中为allCardColumnMappingFieldPropertyEntity .GroupBy(column => (column.FieldDesc + column.OutputColumnId)) .ToDictionary(groupElement => groupElement.Key, groupElement => (object)groupElement.Select(currentElement => { currentElement.FieldPropertyMapping = fieldPropertyEntity .Where(field => field.OutputColumnId == currentElement.OutputColumnId) .Where(field => field.FieldDesc == currentElement.FieldDesc) .ToDictionary(property => property.PropertyDesc, property => property.PropertyValue); return currentElement; }).FirstOrDefault());

currentElement.FieldPropertyMapping

我们在当前代码中遇到的挑战我们不能随时将Where视为null,即使allCardColumnMappingFieldPropertyEntity .GroupBy(column => (column.FieldDesc + column.OutputColumnId)) .ToDictionary(groupElement => groupElement.Key, groupElement => (object)groupElement.Select(currentElement => { List<DesignCardFieldProperty> localDesignCardFieldPropertyEntity = fieldPropertyEntity .Where(field => field.OutputColumnId == currentElement.OutputColumnId) .Where(field => field.FieldDesc == currentElement.FieldDesc).ToList(); if(localDesignCardFieldPropertyEntity.Any()) currentElement.FieldPropertyMapping = localDesignCardFieldPropertyEntity .ToDictionary(property => property.PropertyDesc, property => property.PropertyValue); return currentElement; }).FirstOrDefault()); 子句找不到匹配的记录它总是会导致空字典,但我们有业务需求如果它为空,则使其为null。我已完成以下修改以满足条件,但可能有更好的方法在Linq代码中实现它,任何指针/建议

修改后的代码

for(int i = 0 ; i < sqrt(number) ; i++)
{
    //some operations
}

1 个答案:

答案 0 :(得分:1)

尝试简单的扩展方法

public static class Extensions
{
    public static IDictionary<TKey, TValue> NullIfEmpty<TKey, TValue>(this IDictionary<TKey, TValue> dictionary)
    {
        if (dictionary == null || !dictionary.Any())
        {
            return null;
        }
        return dictionary;
    }
}
相关问题