Search code examples
c#linqstringcollection

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
                               

Solution

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