Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line LINQ to flatten string[] to a string?

Tags:

c#

.net

linq

I came up with the foreach below but I am hoping this can be accomplished in one line.. maybe linq? Any ideas would be appreciated.

foreach (string item in decoder.AllKeys)
{
    message += String.Format("{0}: {1} ;", item, decoder[item]);
}
like image 1000
TruMan1 Avatar asked May 22 '11 16:05

TruMan1


2 Answers

var message = string.Join(
    ";", 
    decoder.AllKeys
           .Select(x => string.Format("{0}: {1} ", x, decoder[item]))
           .ToArray()
);
like image 189
Darin Dimitrov Avatar answered Sep 21 '22 06:09

Darin Dimitrov


If you're in .NET 4.0, you can use this:

string message = string.Join(" ;", decoder.AllKeys
    .Select(k => string.Format("{0}: {1}", k, decoder[k]));

If you're not on .NET 4.0 yet, you need to convert the collection to an array:

string message = string.Join(" ;", decoder.AllKeys
    .Select(k => string.Format("{0}: {1}", k, decoder[k]).ToArray());
like image 39
Lasse V. Karlsen Avatar answered Sep 20 '22 06:09

Lasse V. Karlsen