合併列表中的全部字符串 使用LINQ

是否有任何簡單的LINQ表達式將個人整個List<string>集合項鍊接到帶有定界符的單個stringide

若是集合是自定義對象而不是string怎麼辦? 想象一下,我須要在object.Nameobject.Namethis


#1樓

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));

#2樓

我認爲,若是您在擴展方法中定義邏輯,則代碼將更具可讀性: 編碼

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(", ");

#3樓

我已經使用LINQ作到了: spa

var oCSP = (from P in db.Products select new { P.ProductName });

string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));

#4樓

您能夠簡單地使用: code

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

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

編碼愉快! orm


#5樓

在.NET 4.0或更高版本中: 對象

String.Join(delimiter, list);

足夠了。 get

相關文章
相關標籤/搜索