开发者

How to serialize the Key and only one object value of a generic Dictionary<TKey, TValue>?

开发者 https://www.devze.com 2023-01-20 08:06 出处:网络
I am looking forward to serialize a Dictionary in order to save some of it\'s information, more precisely it\'s Key and one of it\'s Value, into Silverlight Isolated storage. I have read many question

I am looking forward to serialize a Dictionary in order to save some of it's information, more precisely it's Key and one of it's Value, into Silverlight Isolated storage. I have read many question talking about the same subject on these boards, but none were explaining what I was trying to do, o开发者_运维知识库r at least not in a way I could understand. I also don't know with what I could serialize it: XmlSerializer, JSON, etc... I am trying to perform this serialization in order to 'save' some of the user settings, I don't intend to send them to a Web service or anything, it's only use will be inside the application.

Here is the structure of my Dictionary:

static Dictionary<string, User> Mydictionary

And here is the 'User' class:

public class User
{
    public User()
    {

    }

    public string name;
    public string age;
    public string groups;
}

I would like to save the Key and the 'groups' Value of my object and serialize only those two informations. I was asking myself if it was even possible?

Thank you, Ephismen.


Serializin/deserializing XML with Linq is very easy, I strongly recommend you take a look at it if you don't know it yet.

Serialization will look like this:

// add reference to System.Xml.Linq

var xml = new XDocument(
    new XDeclaration("1.0", "utf-8", "yes"),
    new XElement("users",
    from pair in dic
    select new XElement("user",
        new XAttribute("userId", pair.Key),
        new XAttribute("Groups", pair.Value.groups))));

// xml.Save(...) to save in the IsolatedStorage

Deserialization:

XDocument loaded = XDocument.Load(...your stream...);

var results = from c in loaded.Descendants("users")
        select new {
            userIdAttribute = (string)c.Attribute("userId"),
            groupsAttribute = (string)c.Element("Groups")
        };

foreach (var user in results)
{
    dic.Add(user.userIdAttribute,
        new User()
        {
            name = user.userIdAttribute,
            groups = user.groupsAttribute
        });
}

You can find some good documentation here and some examples here.

0

精彩评论

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

关注公众号