开发者

Best way to update data in a Class array from an xml [C#, Linq, XML]

I am in doubt about how to update a dictionary in a class array. I load the upgrade from an xml inside the xml there are indices of the updated data.

I would have been updated according to update the data contained within each class in the array...

My data structure is this:

public class ContactData
{
    public int UID { get; set; }
    public string Status { get; 开发者_Python百科set; }
    ...
}

from the xml i get this:

<?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>

Then, i have to update ContactData[] contacts only by xml uids...

Contacts can be 1000 over length, xml can have same length...

How to perform a fast update?

EDIT:

I used this way:

        XDocument doc = XDocument.Load("http://localhost/contact/xml/status.php");
        foreach (XElement node in doc.Descendants("update"))
        {
            var item = contactList.ListBox.Items.OfType<ContactData>().Where(i => i.UserID.ToString() == node.Element("uid").Value);
            ContactData[] its = item.ToArray();
            if (its.Length > 0) its[0].Data["state"] = node.Element("state").Value;
        }


I would have a Dictionary<int, string>, which offers very fast access to keys, so you can test if a key exists. If it doesn't exist, insert it, if it exists either complain or update it.

At the very end, you can build new ContactData objects from each KeyValuePair<int, string> in your dictionary.

That should be fast enough for most situations.

Update: load your existing ContactData[] into a dictionary:

foreach (ContactData cd in myData)
{
    if (!dict.ContainsKey(cd.UID)) // Omit if you know they are unique.
        dict.Add(cd.UID, cd.Status);
}

You then have three options off the top of my head:

  1. XmlDocument load the XML into this and then pull out your ContactData elements, read those into the dictionary in a foreach.
  2. XmlReader forward-only readers to stream the XML and as you stream, populate the dictionary.
  3. LINQ to XML, an example escapes me, but the net result it you will select the elements out likely as anonymous types and can then populate your dictionary. In fact, Linq might be able to let you filter out duplicates - avoiding the need for the dictionary if you get clever.

Then at the very end, bin your array (or flush it and resize it), then populate it from the dictionary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜