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

本文关键字:字符串 分隔 一个 LINQ 何使用 集合 | 更新日期: 2023-09-27 18:22:41

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

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

我现在想输出这个:

title1;title2;title3;title4

我该怎么做?

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

使用String.Join方法

使用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);
string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));

由于.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));