[ACCEPTED]-Convert List<string> to StringCollection-string
Accepted answer
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();
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
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;
}
}
I would prefer:
Collection<string> collection = new Collection<string>(theList);
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.