替换为Linq的if和foreach

时间:2016-04-07 16:11:45

标签: c# linq

以下代码是否有复杂的LINQ? 我的代码试图通过首先获取另一个字典中的对象列表然后循环到该对象列表来准备字符串(键),字符串(值)的字典。

Dictionary<string, string> displayNames = new Dictionary<string, string>();
List<DefDefaultDataSet.dbEnumsRow> enumList;

//allEnums dictionary: Key as string and value as List<DefDefaultDataSet.dbEnumsRow>
//enumID is a string object
if (allEnums.TryGetValue(enumID, out enumList))
{
   foreach (DefDefaultDataSet.dbEnumsRow row in enumList)
   {
       string enumValue = row.Value;
       //If already have enumvalue ,no need to add again
       if (!string.IsNullOrWhiteSpace(enumValue) && !displayNames.ContainsKey(enumValue))
       {
            displayNames.Add(enumValue, FindResourceVal(row.ResourceKey, uniqueKey));
       }
   }
}

1 个答案:

答案 0 :(得分:0)

您可以保留if语句,然后使用Where进行过滤,并使用ToDictinary创建字典:

if (allEnums.TryGetValue(enumID, out enumList))
    displayNames = enumList.Where(e => !string.IsNullOrWhiteSpace(e.Value) && !displayNames.ContainsKey(e.Value))
                           .ToDictionary(k => k.ResourceKey, v => FindResourceVal(v.ResourceKey, uniqueKey));