【问题标题】:Merge two string arrays in .NET/C# 2.0? [duplicate]在 .NET/C# 2.0 中合并两个字符串数组? [复制]
【发布时间】:2012-07-25 20:29:29
【问题描述】:

可能重复:
Merging two arrays in .NET
How do I concatenate two arrays in C#?

如何合并两个 string[] 变量?

例子:

string[] x = new string[] { "apple", "soup", "wizard" };
string[] y = new string[] { Q.displayName, Q.ID.toString(), "no more cheese" };

我想添加这两个,所以x 的内容按顺序是:{"apple", "soup", "wizard",Q.displayName, Q.ID.toString(), "no more cheese"};。这可能吗?如果结果必须进入一个新的字符串数组,那很好;我只是想知道如何实现它。

【问题讨论】:

标签: c# .net arrays string c#-2.0


【解决方案1】:

来自this answer

var z = new string[x.length + y.length];
x.CopyTo(z, 0);
y.CopyTo(z, x.length);

【讨论】:

    【解决方案2】:

    你可以试试:

    string[] a = new string[] { "A"};
    string[] b = new string[] { "B"};
    
    string[] concat = new string[a.Length + b.Length];
    
    a.CopyTo(concat, 0);
    b.CopyTo(concat, a.Length);
    

    那么concat 就是你的串联数组。

    【讨论】:

    • 对不起老兄,它是 2.0 没有 .concat 之类的东西
    【解决方案3】:

    由于您提到 .NET 2.0 并且 LINQ 不可用,您真的被困在“手动”中:

    string[] newArray = new string[x.Length + y.Length];
    for(int i = 0; i<x.Length; i++)
    {
       newArray[i] = x[i];
    }
    
    for(int i = 0; i<y.Length; i++)
    {
       newArray[i + x.Length] = y[i];
    }
    

    【讨论】:

      【解决方案4】:

      试试这个。

           string[] front = { "foo", "test","hello" , "world" };
           string[] back = { "apple", "soup", "wizard", "etc" };
      
      
           string[] combined = new string[front.Length + back.Length];
           Array.Copy(front, combined, front.Length);
           Array.Copy(back, 0, combined, front.Length, back.Length);
      

      【讨论】:

        猜你喜欢
        • 2018-09-24
        • 2017-08-12
        • 2021-07-28
        • 2013-12-16
        • 2016-06-18
        • 1970-01-01
        • 2010-09-08
        • 1970-01-01
        • 2017-09-16
        相关资源
        最近更新 更多