如何在 C# 中将两个 StringCollection 组合/合并为一个

How to combine / merge two StringCollection into one in C#

How to combine / merge two StringCollection in C#

var collection1 = new StringCollection () { "AA", "BB", "CC" };
var collection2 = new StringCollection () { "DD", "EE", "FF" };
var resultCollection = collection1 + collection2 ; // TODO
                               

您可以转换为数组并使用 Union,请注意这也会删除重复项

var resultCollection = collection1.Cast<string>().Union(collection2.Cast<string>())

您可以像这样将所有内容复制到一个数组中

    var collection1 = new StringCollection() { "AA", "BB", "CC" };
    var collection2 = new StringCollection() { "DD", "EE", "FF" };

    var array = new string[collection2.Count + collection1.Count];

    collection1.CopyTo(array, 0);
    collection2.CopyTo(array, collection1.Count);

您可以占用 List 而不是 StringCollection ...

        var collection1 = new List<string>() { "AA", "BB", "CC" };
        var collection2 = new List<string>() { "DD", "EE", "FF" };
        var resultCollection = collection1.Concat(collection2).ToList();

如果你仍然想要一个字符串集合,你可以使用 AddRange

var collection1 = new StringCollection () { "AA", "BB", "CC" };
var collection2 = new StringCollection () { "DD", "EE", "FF" };
var resultCollection = new StringCollection();
resultCollection.AddRange(collection1.Cast<string>.ToArray());
resultCollection.AddRange(collection2.Cast<string>.ToArray());

似乎很奇怪 StringCollection 不直接支持添加其他 StringCollection。如果效率是一个问题, 可能比这里的答案更有效,如果你仍然需要它在 StringCollection 中,你可以获取生成的数组并使用 AddRange 添加该字符串数组到一个新的 StringCollection