Concat all strings inside a List<string> using LINQ
Is there any easy LINQ expression to concatenate my entire List<string>
collection items to a single string
with a delimiter character?
What if the collection is of custom objects instead of string
? Imagine I need to concatenate on object.Name
.
By using LINQ, this should work;
string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));
class description:
public class Foo
{
public string Boo { get; set; }
}
Usage:
class Program
{
static void Main(string[] args)
{
string delimiter = ",";
List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };
Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
Console.ReadKey();
}
}
And here is my best :)
items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)
In .NET 4.0 and later:
String.Join(delimiter, list);
is sufficient. For older versions you have to:
String.Join(delimiter, list.ToArray());
This is for a string array:
string.Join(delimiter, array);
This is for a List<string>:
string.Join(delimiter, list.ToArray());
And this is for a list of custom objects:
string.Join(delimiter, list.Select(i => i.Boo).ToArray());
链接地址: http://www.djcxy.com/p/52748.html
上一篇: foreach循环和数组值