[ACCEPTED]-Convert List<string> to StringCollection-string

Accepted answer
Score: 36

How about:

StringCollection collection = new StringCollection();
collection.AddRange(list.ToArray());

Alternatively, avoiding the intermediate 2 array (but possibly involving more reallocations):

StringCollection collection = new StringCollection();
foreach (string element in list)
{
    collection.Add(element);
}

Converting 1 back is easy with LINQ:

List<string> list = collection.Cast<string>().ToList();
Score: 2

Use List.ToArray() which will convert List to an Array 2 which you can use to add values in your 1 StringCollection.

StringCollection sc = new StringCollection();
sc.AddRange(mylist.ToArray());

//use sc here.

Read this

Score: 0

Here's an extension method to convert an 2 IEnumerable<string> to a StringCollection. It works the same way as the other 1 answers, just wraps it up.

public static class IEnumerableStringExtensions
{
    public static StringCollection ToStringCollection(this IEnumerable<string> strings)
    {
        var stringCollection = new StringCollection();
        foreach (string s in strings)
            stringCollection.Add(s);
        return stringCollection;
    }
}
Score: 0

I would prefer:

Collection<string> collection = new Collection<string>(theList);

0

More Related questions