简体   繁体   English

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

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

How to combine / merge two StringCollection in C#如何在C#中组合/合并两个StringCollection

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

You can copy all to an array like this您可以将所有内容复制到这样的数组中

    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);

If you still want a string collection you can just use AddRange如果你仍然想要一个字符串集合,你可以使用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());

Seems odd that StringCollection doesn't have any direct support for adding other StringCollection s. StringCollection对添加其他StringCollection没有任何直接支持,这似乎很奇怪。 If efficiency is a concern, Beingnin's answer is probably more efficient than the answer here, and if you still need it in a StringCollection you can take the array that is generated and use AddRange to add that array of strings to a new StringCollection如果效率是一个问题, Beingnin 的答案可能比这里的答案更有效,如果您仍然需要在StringCollection中使用它,您可以获取生成的数组并使用AddRange将该字符串数组添加到新的StringCollection

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

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

you can occupy List instead of StringCollection ...你可以占用 List 而不是 StringCollection ...

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM