Concat的内部名单,其中的所有字符串,字符串>使用LINQ字符串、名单、Concat、GT

2023-09-08 08:44:06 作者:我们就像刺猬、伤着彼此

有一个简单的LINQ EX pression来连接我的整个列表<字符串>藏品到一个字符串与分隔符

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)