Nathan DeWitt
Nathan DeWitt

Reputation: 6601

How do I use LINQ to reduce a collection of strings to one delimited string?

I have a list of strings and I want to dump them out as a string with semi-colon delimiters.

IEnumerable<string> foo = from f in fooList
                          where f.property == "bar"
                          select f.title;

I now want to output this:

title1;title2;title3;title4

How do I do that?

Upvotes: 9

Views: 4119

Answers (4)

Dan J
Dan J

Reputation: 16718

Since .NET 2.0, the string class provides a convenient Join method. While it originally operated on arrays only, .NET 4 adds an IEnumerable overload...

IEnumerable<string> foo = from f in fooList
                          where f.property == "bar"
                          select f.title;

Console.WriteLine(string.Join(";", foo));

Upvotes: 6

zellio
zellio

Reputation: 32514

Using LINQ instead of String.Join as that was what was asked for. Though really String.Join is probably a safer / easier bet.

IEnumerable<string> foo = from f in fooList
                      where f.property == "bar"
                      select f.title;
string join = foo.Aggregate((s, n) => s + ";" + n);

Upvotes: 15

BrokenGlass
BrokenGlass

Reputation: 160952

string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));

Upvotes: 11

mservidio
mservidio

Reputation: 13057

Use the String.Join Method

Upvotes: 16

Related Questions