如何使用LINQ将字符串集合减少为一个分隔字符串?

时间:2012-02-03 17:43:33

标签: c# linq

我有一个字符串列表,我想将它们作为带有分号分隔符的字符串转储出来。

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

我现在要输出这个:

title1;title2;title3;title4

我该怎么做?

4 个答案:

答案 0 :(得分:15)

答案 1 :(得分:10)

使用LINQ而不是String.Join就是这样要求的。虽然真的String.Join可能是一个更安全/更容易的赌注。

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

答案 2 :(得分:6)

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

答案 3 :(得分:4)

从.NET 2.0开始,字符串类提供了方便的Join方法。虽然它最初只在阵列上运行,但.NET 4增加了IEnumerable重载......

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

Console.WriteLine(string.Join(";", foo));
相关问题