2016-04-07 58 views
1

對於下面的代碼是否有複雜的LINQ? 我的代碼試圖準備一個字符串(鍵),字符串(值)的字典,首先從另一個字典中獲取對象列表,然後循環到該對象列表。Linq的替代if和foreach

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)); 
     } 
    } 
} 
+0

請問你的代碼的工作?如果它確實考慮在其他地方詢問,因爲此站點存在代碼不起作用的問題 – TheLethalCoder

+0

是的,它確實有效。 –

+0

你能提供一些樣本數據嗎?在我看來,你可以使用'ToDictionary()',但很難在沒有看到整個事物(加​​上數據)的情況下推理你的代碼。 –

回答

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));