Concat的内部名单,其中的所有字符串,字符串&GT;使用LINQ [英] Concat all strings inside a List<string> using LINQ
本文介绍了Concat的内部名单,其中的所有字符串,字符串&GT;使用LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个简单的LINQ EX pression来连接我的整个列表&LT;字符串>藏品到一个字符串与分隔符
Is there an easy LINQ expression to concatenate my entire List<string> collection items to a single string with a delimiter character?
如果集合是自定义对象,而不是字符串?想象一下,我需要Concat的上object.Name。
What if the collection is of custom objects instead of String? Imagine I need to concat on object.Name.
推荐答案
使用LINQ,这应该工作;
By using LINQ, this should work;
string delimeter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimeter + j));
类描述:
public class Foo
{
public string Boo { get; set; }
}
用法:
class Program
{
static void Main(string[] args)
{
string delimeter = ",";
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 + delimeter + j.Boo)}).Boo);
Console.ReadKey();
}
}
这里是我最好的:)
And here is my best :)
items.Select(i => i.Boo).Aggregate((i, j) => i + delimeter + j)
这篇关于Concat的内部名单,其中的所有字符串,字符串&GT;使用LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文