1

I working with a string like this:

Norway, true; Sweden, false; England, null; Denmark, false;

I'm trying to get that into a Dictionary<string, bool?> so I can work with it, remove items, compare against other stuff. When I'm done, I want to convert the dictionary back to a similar string and save it.

Any ideas?

4

1 回答 1

6

Split您可以使用方法和 LINQ将其转换为字典:

var dict = str.Split(';')
    .Select(s => s.Split(','))
    .ToDictionary(
        p => p[0].Trim()
    ,   p => p[1].Trim().Equals("null") ? null : (bool?)(bool.Parse(p[1].Trim()))
    );

转换回来更容易:

var res = string.Join("; ", dict.Select(
    p => string.Format(
        "{0}, {1}"
    ,   p.Key
    ,   p.Value.HasValue ? p.Value.ToString().ToLowerCase() : "null"
    )
));
于 2013-08-07T13:28:12.183 回答