Assume there is a list:
var rawItems = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string,string>("A", "1"),
new KeyValuePair<string,string>("B", "2"),
new KeyValuePair<string,string>("C", "3")
};
And it is needed to construct a string int the following form:
A = 1,
B = 2,
C = 3
The method being used:
List<string> transformedItems = new List<string>();
rawItems.ForEach(item => transformedItems.Add(item.Key + " = " + item.Value));
string result = String.Join("," + Environment.NewLine, transformedItems.ToArray());
I would be gladly surprised if someone could think of a more elegant way of doing this.
P.S.: Not necessarily "same code packed in one line" type of solution but rather another way.
Perhaps you'll find this "elegant":
var result = string.Join(",\r\n", rawItems.Select(
x => string.Format("{0} = {1}", x.Key, x.Value)));
I usually define an extension method for Join (in a static class somewhere):
static string StringJoin<T>(this IEnumerable<T> values, string separator)
{
return string.Join(separator, values);
}
Then you can rewrite your code as follows:
string result =
rawItems
.Select(item => item.Key + " = " + item.Value)
.StringJoin("," + Environment.NewLine);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With