9

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?

Nathan DeWitt
  • 6,511
  • 8
  • 46
  • 66
  • Possible duplicate http://stackoverflow.com/questions/122670/what-is-the-linq-way-to-implode-join-a-string-array – Paul Feb 03 '12 at 17:45
  • 1
    Not sure why you need to use linq to perform that...just use string.join like suggested. – Rig Feb 03 '12 at 17:46
  • @Rig he probably expected a built-in reduce method, because most functional languages come with it. And indeed Aggregate is LINQ's reduce implementation. – Jan Mar 19 '14 at 17:51

4 Answers4

16

Use the String.Join Method

mservidio
  • 12,817
  • 9
  • 58
  • 84
14

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);
zellio
  • 31,308
  • 1
  • 42
  • 61
11
string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
6

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));
Dan J
  • 16,319
  • 7
  • 50
  • 82
  • 1
    It's worth mentioning that this particular overload (taking an `IEnumerable` as parameter) was only added in .NET 4 – BrokenGlass Feb 03 '12 at 18:40