2017-04-04 26 views
0

我必須把的XElement的XElement與值[ABC INC,假]進入Dictionary<string, bool?>Lambda表達式添加的XElement到字典

我結束了一段代碼:

Dictionary<string, bool?> LogicalDistinctValues; 
      foreach (XElement xelement in lvalues.Elements()) 
      { 
       string[] vals = xelement.Value.Replace("[", string.Empty).Replace("]", string.Empty).Split(','); 
       if (vals.Count() == 2) 
       { 
        string val; 
        bool lval; 
        val = vals[0]; 
        if(bool.TryParse(vals[1], out lval)) 
        { 
         LogicalDistinctValues.Add(val, lval); 
        } 
        else 
        { 
         LogicalDistinctValues.Add(val, true); 
        } 
       } 
      } 

是否有可能取代它用lambda表達式?

+1

在Split()之前不需要'ToString()', – xanatos

回答

2

我做得難看這裏的東西,你不應該永遠做。這段代碼比你的代碼慢,而且比較醜。

bool lval; 

Dictionary<string, bool?> LogicalDistinctValues = 
    (from xelement in lvalues.Elements() 
     let vals = xelement.Value.Replace("[", string.Empty).Replace("]", string.Empty).Split(',') 
     where vals.Length == 2 
     select new { Key = vals[0], Value = bool.TryParse(vals[1], out lval) ? (bool?)lval : true } 
    ).ToDictionary(x => x.Key, x => x.Value); 
} 

注意,我做壞事......我做了out一個局部變量。這在LINQ表達式中通常在道德上是錯誤的。

作爲旁註,您使用了無用的.ToString()而不是.Count()您應該使用.Length作爲數組。

請注意,我從頭開始創建Dictionary<>。如果你需要添加元素到一個已經存在的數組中,那麼你不能直接在LINQ中完成它(因爲Dictionary<>沒有AddRange)...你可以做一個foreach,結果是select

var exp = from xelement in lvalues.Elements() 
      let vals = xelement.Value.Replace("[", string.Empty).Replace("]", string.Empty).Split(',') 
      where vals.Length == 2 
      select new { Key = vals[0], Value = bool.TryParse(vals[1], out lval) ? (bool?)lval : true }; 

foreach (var kv in exp) 
{ 
    LogicalDistinctValues.Add(kv.Key, kv.Value); 
} 
2

我想你可以做這樣的事情。這是一個有點難看,但這樣你會做一氣呵成:

bool lval; 
var LogicalDistinctValues= (
     from xelement in lvalues.Elements() 
     let vals = xelement.Value.Replace("[", string.Empty).Replace("]", string.Empty).ToString().Split(',') 
     where vals.Count() ==2 
     select new 
     { 
      Key= vals[0], 
      Value=bool.TryParse(vals[1],out lval)?lval:true 
     } 
    ).ToDictionary (l =>l.Key,l=>l.Value);