是否有任何簡單的LINQ表達式將個人整個List<string>
集合項鍊接到帶有定界符的單個string
? ide
若是集合是自定義對象而不是string
怎麼辦? 想象一下,我須要在object.Name
上object.Name
。 this
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));
我認爲,若是您在擴展方法中定義邏輯,則代碼將更具可讀性: 編碼
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作到了: spa
var oCSP = (from P in db.Products select new { P.ProductName }); string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));
您能夠簡單地使用: code
List<string> items = new List<string>() { "foo", "boo", "john", "doe" }; Console.WriteLine(string.Join(",", items));
編碼愉快! orm
在.NET 4.0或更高版本中: 對象
String.Join(delimiter, list);
足夠了。 get