可枚举.包含两个以上的参数c#



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

第一个:xxxxxxxx第二个:xx第三个:xxxxxxxx第四个:xx

我想连接这4个集合以获得:xxxxxxxxxxxxxxx

我想使用Enumerable.Concat,但我有一个问题,它只需要两个参数。因此,我只能把第一个和第二个连在一起(例如),但不能把它们全部连在一起。

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

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

编辑

我犯了一个错误,我想加入4个系列。这些集合包含如前所示的字符串,但这些是集合

您可以像这样链接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方法,其余都一样。

您应该使用string.Concat方法,Enumerable.Concat用于集合。

您也可以使用+运算符。

请注意,字符串是不可变的对象。这意味着当添加2个字符串时,将创建一个新的字符串对象。因此,出于内存优化的目的,应该将StringBuilder类用于动态字符串和5个以上字符串的串联。

如果只有四个字符串,有什么问题

first+ second+ third+ forth;

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

首先,请注意,String.Concat()的过载占用一到四个string参数。

其次,请注意,编译器将把涉及四个或更少字符串的串联转换为对适当的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个字符串的速度提高。


[EDIT]好的,OP完全把问题从串联字符串改为串联字符串集合。。。所以这个答案现在毫无意义(

最新更新