Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

linq

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?

like image 232
Nathan DeWitt Avatar asked Feb 03 '12 17:02

Nathan DeWitt


4 Answers

Use the String.Join Method

like image 151
mservidio Avatar answered Oct 18 '22 18:10

mservidio


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);
like image 28
zellio Avatar answered Oct 18 '22 18:10

zellio


string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));
like image 11
BrokenGlass Avatar answered Oct 18 '22 17:10

BrokenGlass


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));
like image 6
Dan J Avatar answered Oct 18 '22 17:10

Dan J