2017-03-03 38 views
0

如何建立密鑰對列表(INT鍵,字符串值?),並刷新後,我得到新的XML:建設和刷新靜態列表

 List<KvPair> source = new List<KvPair> 
     { 
      new KvPair {Key = null, Value = "Null"}, 
      new KvPair {Key = 0, Value = "No"}, 
      new KvPair {Key = 1, Value = "Yes"} 

     }; 

列表取決於從XML。如果我將刷新列表,並且會從XML只得到2個值:NULL,0,那麼列表應該只有2個元素:

new KvPair {Key = null, Value = "Null"}, 
    new KvPair {Key = 1, Value = "Yes"} 

我應該使用靜態列表? 比這更好的方式:

private List<KvPair> RebuildList(object extendData) //extendedData is xml 
    { 
    List<KvPair> source = new List<KvPair> 
    { 
     new KvPair {Key = null, Value = "Null"}, 
     new KvPair {Key = 0, Value = "No"}, 
     new KvPair {Key = 1, Value = "Yes"}  
    }; 
    List<int> target = new List<int>(); 
    var data = XDocument.Parse(extendData.ToString()).Descendants("elem"); 
    int tempVal; 

    foreach (var elem in data) 
    { 
     var key = Int32.TryParse(elem.Attribute("Value").Value, 
      out tempVal) ? tempVal : null; 
     target.Add(key) 
    } 
    source.RemoveAll(x => !target.Contains(x)); 

    return new List<KvPair>(source); 
} 

回答

0

您更好地實現自己的類將與列表下工作,但你會實現自己的Add方法,在那裏你會刷新你的列表,你在添加之前希望。