使用LINQ对List <string>中的所有string进行Concat
有没有任何简单的LINQexpression式来连接我的整个List<string>集合项目与一个带有分隔符字符的单个string ? 
 如果集合是自定义对象而不是string呢? 想象一下,我需要连接在object.Name 。 
通过使用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) 
在.NET 4.0和更高版本中:
 String.Join(delimiter, list); 
足够了。 对于旧版本,您必须:
 String.Join(delimiter, list.ToArray()); 
这是一个string数组:
 string.Join(delimiter, array); 
这是一个List <string>:
 string.Join(delimiter, list.ToArray()); 
这是一个自定义对象的列表:
 string.Join(delimiter, list.Select(i => i.Boo).ToArray()); 
 using System.Linq; public class Person { string FirstName { get; set; } string LastName { get; set; } } List<Person> persons = new List<Person>(); string listOfPersons = string.Join(",", persons.Select(p => p.FirstName)); 
好问题。 我一直在使用
 List<string> myStrings = new List<string>{ "ours", "mine", "yours"}; string joinedString = string.Join(", ", myStrings.ToArray()); 
这不是LINQ,但它的工作原理。
 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(", ");