Enumerable.Concat两个以上的参数c#

时间:2014-09-22 08:02:00

标签: c# string concat enumerable

我有4个包含字符串的集合,如下所示:

首先:xxxxxxxx 第二个:xx 第三名:xxxxxxxx 第四名:xx

我想将这4个集合连接起来:xxxxxxxxxxxxxxxxxxxx

我想使用Enumerable.Concat但我有一个问题,它只需要两个参数。因此,我只能将第一个与第二个(例如)连在一起,但不能将所有'连在一起。

c#是否提供了将两个以上的集合连接在一起的方法?

我是否必须创建两个集合,其中第一个+第二个和第三个+第四个,然后将两个集合连接在一起?

修改

我犯了一个错误,这是我想要连接的4个收藏品。这些集合包含如前所示的字符串,但这些是集合

4 个答案:

答案 0 :(得分:1)

您可以像这样链接Enumerable.Concat来电。

List<string> list1 = new List<string>();
List<string> list2 = new List<string>();
List<string> list3 = new List<string>();
List<string> list4 = new List<string>();

//Populate the lists

var mergedList = list1.Concat(list2)
    .Concat(list3)
    .Concat(list4)
    .ToList();

另一个选择是创建一个数组并调用SelectMany

var mergedList = new[]
{
    list1, list2, list3, list4
}
.SelectMany(x => x)
.ToList();

注意:Enumerable.Concat将允许重复元素,如果您想要消除重复项,可以使用Enumerable.Union方法,其余部分都一样。

答案 1 :(得分:0)

您应该使用string.Concat方法,Enumerable.Concat用于收藏。

您也可以使用+运算符。

请注意,字符串是不可变对象。这意味着当您添加2个字符串时,正在创建一个新的字符串对象。因此,出于内存优化的目的,您应该将StringBuilder类用于动态字符串并连接超过5个字符串。

答案 2 :(得分:0)

如果它只有四个字符串,那就错了:

first+ second+ third+ forth;

???

答案 3 :(得分:0)

如果你连接4个或更少的字符串,你自己不需要采取任何特殊行动。

首先,请注意there are overloads of String.Concat() taking between one and four string parameters

其次,请注意编译器会将涉及四个或更少字符串的连接转换为对相应String.Concat()重载的调用。

例如,请考虑以下代码:

string a = "a";
string b = "b";
string c = "c";
string d = "d";
string e = a + b + c + d;

连接变成了这个IL:

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 4
    .locals init (
        [0] string a,
        [1] string b,
        [2] string c,
        [3] string d,
        [4] string e)
    L_0000: ldstr "a"
    L_0005: stloc.0 
    L_0006: ldstr "b"
    L_000b: stloc.1 
    L_000c: ldstr "c"
    L_0011: stloc.2 
    L_0012: ldstr "d"
    L_0017: stloc.3 
    L_0018: ldloc.0 
    L_0019: ldloc.1 
    L_001a: ldloc.2 
    L_001b: ldloc.3 
    L_001c: call string [mscorlib]System.String::Concat(string, string, string, string)
    L_0021: stloc.s e
    L_0023: ldloc.s e
    L_0025: call void [mscorlib]System.Console::WriteLine(string)
    L_002a: ret 
}

请注意,实际连接是通过调用System.String::Concat(string, string, string, string)完成的。

如果要连接更多字符串,您可能需要考虑使用StringBuilder,但是您可能只会看到超过8个字符串的速度提升。


[编辑]好的,OP完全改变了从连接字符串到连接字符串集合的问题......所以这个答案现在毫无意义。 :(