8

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,421
  • 8
  • 44
  • 65
  • 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

15

Use the String.Join Method

mservidio
  • 12,404
  • 8
  • 54
  • 82
13

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
  • 28,131
  • 1
  • 39
  • 59
10
string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));
BrokenGlass
  • 153,880
  • 28
  • 280
  • 327
5

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
  • 15,852
  • 6
  • 49
  • 79
  • 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