TruMan1
TruMan1

Reputation: 36128

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

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]);
}

Upvotes: 13

Views: 10669

Answers (6)

dhruvin
dhruvin

Reputation: 807

The String class from BCL already supports this. Here is a one liner to achieve this using String class. I would always use the BCL operation if it's available there considering the MS guys would have already taken the pain to optimize such a crucial class.

String.Join(";", decoder.AllKeys);

Here is the link to the MSDN for all the variants of this method - http://goo.gl/kmwfYt

Upvotes: 7

Amy B
Amy B

Reputation: 110171

IEnumerable<string> query =
  from KeyValuePair<string, string> kvp in decoder
  select String.Format("{0}: {1} ;", kvp.Key, kvp.Value);

string result = string.Join(null, query);

Upvotes: 1

Patrick McDonald
Patrick McDonald

Reputation: 65451

If you already have a Join extension method on IEnumerable like I have:

public static string Join(this IEnumerable<string> values, string separator)
{
    return string.Join(separator, values);
}

then the rest is just a one-liner:

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

Note that if you're not using .NET 4, then you can replace the implementation of the extension method to whatever works for your version.

EDIT: Even better, create the following extension method:

public static string Join(this IEnumerable<string> values, string separator, Func<string, string> selector)
{
    return string.Join(separator, values.Select(selector));
}

and call it as follows:

decoder.AllKeys.Join(";", item => String.Format("{0}: {1}", item, decoder[item]));

you won't get more one-line than that, other than putting an extension method on NameValueCollection, or whatever decoder is :)

Upvotes: 0

sarvesh
sarvesh

Reputation: 2743

This should work.

decoder.AllKeys.Aggregate("", (current, item) => current + String.Format("{0}: {1} ;", item, decoder[item]));

Upvotes: 4

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391516

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());

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1039190

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

Upvotes: 16

Related Questions