Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从xml[C,Linq,xml]更新类数组中数据的最佳方法_C#_Xml_Arrays_Linq - Fatal编程技术网

C# 从xml[C,Linq,xml]更新类数组中数据的最佳方法

C# 从xml[C,Linq,xml]更新类数组中数据的最佳方法,c#,xml,arrays,linq,C#,Xml,Arrays,Linq,我对如何在类数组中更新字典有疑问。 我从xml中加载升级,在xml中有更新数据的索引 我会根据数组中每个类中包含的更新数据进行更新 我的数据结构如下: public class ContactData { public int UID { get; set; } public string Status { get; set; } ... } 从xml中,我得到以下信息: <?xml version=\"1.0\" encoding=\"UTF-8\"?>

我对如何在类数组中更新字典有疑问。 我从xml中加载升级,在xml中有更新数据的索引

我会根据数组中每个类中包含的更新数据进行更新

我的数据结构如下:

public class ContactData
{
    public int UID { get; set; }
    public string Status { get; set; }
    ...
}
从xml中,我得到以下信息:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<status>
   <update>
      <uid>336699</uid>
      <state>My new state</state>
   </update>
   <update>
      <uid>123456</uid>
      <state>new state</state>
   </update>
   <update>
      <uid>111111</uid>
      <state>some state</state>
   </update>
</status>
我会有一个字典,它提供了对密钥的快速访问,因此您可以测试密钥是否存在。如果不存在,请插入它;如果存在,请投诉或更新它

最后,您可以从字典中的每个KeyValuePair构建新的ContactData对象

对于大多数情况,这应该足够快

更新:将现有ContactData[]加载到字典中:

foreach (ContactData cd in myData)
{
    if (!dict.ContainsKey(cd.UID)) // Omit if you know they are unique.
        dict.Add(cd.UID, cd.Status);
}
然后我脑海里就有三个选项:

XmlDocument将XML加载到此文件中,然后取出ContactData元素,将它们读入foreach中的字典。 XmlReader只转发读卡器来流式处理XML,流式处理时,填充字典。 LINQ to XML,我想不出一个例子,但最终的结果是,您将选择可能作为匿名类型的元素,然后可以填充您的字典。事实上,Linq也许可以让你过滤掉重复的内容——如果你聪明的话,就不需要字典了。
然后在最后,对数组进行装箱或刷新并调整其大小,然后从字典中填充它。

我需要更新现有的ContactData[],但如果不对每个元素进行递归搜索,我想不出如何做到这一点。。。
foreach (ContactData cd in myData)
{
    if (!dict.ContainsKey(cd.UID)) // Omit if you know they are unique.
        dict.Add(cd.UID, cd.Status);
}