是否有任何简单的LINQ表达式将我的整个List<string>集合项连接到具有分隔符字符的单个字符串?
如果集合是自定义对象而不是字符串呢?假设我需要连接object。name。
是否有任何简单的LINQ表达式将我的整个List<string>集合项连接到具有分隔符字符的单个字符串?
如果集合是自定义对象而不是字符串呢?假设我需要连接object。name。
当前回答
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> 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(", ");
我已经使用LINQ做到了这一点:
var oCSP = (from P in db.Products select new { P.ProductName });
string joinedString = string.Join(",", oCSP.Select(p => p.ProductName));
您可以使用聚合(Aggregate)将字符串连接成单个字符分隔的字符串,但如果集合为空,则会抛出无效操作异常(Invalid Operation Exception)。
可以将聚合函数与种子字符串一起使用。
var seed = string.Empty;
var seperator = ",";
var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
var carAggregate = cars.Aggregate(seed,
(partialPhrase, word) => $"{partialPhrase}{seperator}{word}").TrimStart(',');
你可以用字符串。Join并不关心您是否传递给它一个空集合。
var seperator = ",";
var cars = new List<string>() { "Ford", "McLaren Senna", "Aston Martin Vanquish"};
var carJoin = string.Join(seperator, cars);
你可以简单地使用:
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(string.Join(",", items));
编码快乐!