开发者

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开发者_C百科.

foreach (string item in decoder.AllKeys)
{
    message += String.Format("{0}: {1} ;", item, decoder[item]);
}


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


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


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


This should work.

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


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


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 :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜