An elegant way to simplify the provided code

Suppose 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 you need to construct an int string like this:

A = 1,
B = 2,
C = 3

      

Method 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 surprised if anyone could think of this more elegant way.

PS: Not necessarily "the same code packed in one line", but a different way.

+3


source to share


2 answers


You might find this "elegant":



var result = string.Join(",\r\n", rawItems.Select(
                                  x => string.Format("{0} = {1}", x.Key, x.Value)));

      

+11


source


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 like this:

string result =
    rawItems
        .Select(item => item.Key + " = " + item.Value)
        .StringJoin("," + Environment.NewLine);

      

+2


source







All Articles