开发者

How to convert Dictionary<string, string> to attribute string in LINQ?

I have a collection of key/values in the form of a D开发者_如何学编程ictionary<string, string>.

How would you convert or aggregate this into an attribute string:

key1="value1" key2="value2" key3="value3"

I believe this can be achieved using Aggregate function, however, I find the documentation on this particular extension method confusing. Any help is much appreciated.


I'd use:

.NET 4:

var text = string.Join(" ", 
              dictionary.Select(pair => string.Format("{0}={1}",
                                pair.Key, pair.Value));

.NET 3.5 (where string.Join has fewer overloads)

var text = string.Join(" ", 
              dictionary.Select(pair => string.Format("{0}={1}",
                                pair.Key, pair.Value)
                        .ToArray());

If you need to do any escaping, do it in the string.Format call. Of course, you don't need to use string.Format - you could use:

var text = string.Join(" ", dict.Select(pair => pair.Key + "=" + pair.Value));

It depends on which you find more readable. (The performance difference will be negligible.)


var dict = new Dictionary<string, string>
                {
                    {"1", "first"},
                    {"2", "second"}
                };

var result = dict.Aggregate(new StringBuilder(),
                            (sb, kvp) => sb.AppendFormat("{0}=\"{1}\" ", kvp.Key, kvp.Value),
                            sb => sb.ToString());


string.Join(" ", myDict.Select(d => string.Format("{0} = {1}", d.Key, d.Value)))


So you want the keys and values of the Dictionary output as a string in this manner? Sounds easy enough:

var myDictionary = new Dictionary<string,string>();
//populate Dictionary

//a Dictionary<string,string> is an IEnumerable<KeyValuePair<sring,string>>
//so, a little Linq magic will work wonders
var myAttributeString = myDictionary.Aggregate(new StringBuilder(), (s, kvp) => s.Append(kvp.Key + "=\"" + (kvp.Value ?? String.Empty) + "\" "));

The result will be a string like the one in your question, with a trailing space (which in XML isn't a huge deal, but you can trim it if you want).

You could also use .NET's XML features to actually put the values into XML as an attribute string of an element. The attribute string will end up in an XML element in a document, which is probably where it needs to go anyway:

XMLDocument doc = new XMLDocument()
XMLElement myElement = doc.CreateElement("myElement")

foreach(var kvp in myDictionary)
   myElement.SetAttribute(kvp.Key, kvp.Value);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜