简体   繁体   中英

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
                               

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

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. 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

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

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

you can occupy List instead of StringCollection ...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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