下面是我的Linq代码,这里我们返回一个Dictionary<string,object>
,同时为每个字符串键填充对象值,我们内部填充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
子句没有找到匹配的记录,它将始终导致空字典,但我们有一个业务需求,使它为空,如果它是空的。我已经做了以下修改,以满足条件,但可能有一个更好的方法来实现它在Linq代码,任何指针/建议
修改代码
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());
尝试使用简单的扩展方法
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;
}
}