Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

An elegant way to simplify the provided code

Tags:

string

c#

list

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.

like image 945
anar khalilov Avatar asked Jun 07 '26 20:06

anar khalilov


2 Answers

Perhaps you'll find this "elegant":

var result = string.Join(",\r\n", rawItems.Select(
                                  x => string.Format("{0} = {1}", x.Key, x.Value)));
like image 199
Yuval Itzchakov Avatar answered Jun 09 '26 12:06

Yuval Itzchakov


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);
like image 39
Patrick McDonald Avatar answered Jun 09 '26 12:06

Patrick McDonald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!