是否有任何简单的LINQ表达式将我的整个List<string>集合项连接到具有分隔符字符的单个字符串?

如果集合是自定义对象而不是字符串呢?假设我需要连接object。name。


当前回答

我认为如果你在扩展方法中定义逻辑,代码将更易于阅读:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

其他回答

警告-严重性能问题

虽然这个答案确实产生了预期的结果,但与这里的其他答案相比,它的性能较差。在决定使用它时要非常谨慎


通过使用LINQ,这应该工作;

string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));

类描述:

public class Foo
{
    public string Boo { get; set; }
}

用法:

class Program
{
    static void Main(string[] args)
    {
        string delimiter = ",";
        List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
            new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };

        Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
        Console.ReadKey();

    }
}

这是我最好的:)

items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)
List<string> strings = new List<string>() { "ABC", "DEF", "GHI" };
string s = strings.Aggregate((a, b) => a + ',' + b);

我认为如果你在扩展方法中定义逻辑,代码将更易于阅读:

public static class EnumerableExtensions { 
  public static string Join<T>(this IEnumerable<T> self, string separator) {  
    return String.Join(separator, self.Select(e => e.ToString()).ToArray()); 
  } 
} 

public class Person {  
  public string FirstName { get; set; }  
  public string LastName { get; set; }  
  public override string ToString() {
    return string.Format("{0} {1}", FirstName, LastName);
  }
}  

// ...

List<Person> people = new List<Person>();
// ...
string fullNames = people.Join(", ");
string lastNames = people.Select(p => p.LastName).Join(", ");

把字符串。连接到扩展方法中。下面是我使用的版本,它比Jordaos的版本更简洁。

当列表为空时返回空字符串""。聚合会抛出异常。 可能比聚合的性能更好 当与其他LINQ方法结合使用时,比纯String.Join()更容易读取

使用

var myStrings = new List<string>() { "a", "b", "c" };
var joinedStrings = myStrings.Join(",");  // "a,b,c"

Extensionmethods类

public static class ExtensionMethods
{
    public static string Join(this IEnumerable<string> texts, string separator)
    {
        return String.Join(separator, texts);
    }
}

你可以简单地使用:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

编码快乐!