连接 List<string> 中的所有字符串使用 LINQ [英] Concat all strings inside a List&lt;string&gt; using LINQ

查看:38
本文介绍了连接 List<string> 中的所有字符串使用 LINQ的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何简单的 LINQ 表达式可以将我的整个 List 集合项连接到一个带有分隔符的 string ?

Is there any easy LINQ expression to concatenate my entire List<string> collection items to a single string with a delimiter character?

如果集合是自定义对象而不是 string 会怎样?想象一下,我需要连接 object.Name.

What if the collection is of custom objects instead of string? Imagine I need to concatenate on object.Name.

推荐答案

警告 - 严重的性能问题

尽管此答案确实产生了预期的结果,但与此处的其他答案相比,它的性能较差.决定使用它时要非常小心

Warning - Serious Performance Issues

Though this answer does produce the desired result, it suffers from poor performance compared to other answers here. Be very careful about deciding to use it

通过使用 LINQ,这应该可以工作;

By using LINQ, this should work;

string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));

类说明:

public class Foo
{
    public string Boo { get; set; }
}

用法:

class Program
{
    static void Main(string[] args)
    {
        string delimiter = ",";
        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 + delimiter + j.Boo)}).Boo);
        Console.ReadKey();

    }
}

这是我最好的:)

items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)

这篇关于连接 List<string> 中的所有字符串使用 LINQ的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆