I need the above feature because I can only store StringCollection to Settings, not List of strings.
How does one convert List into StringCollection?
How about:
StringCollection collection = new StringCollection();
collection.AddRange(list.ToArray());
Alternatively, avoiding the intermediate array (but possibly involving more reallocations):
StringCollection collection = new StringCollection();
foreach (string element in list)
{
collection.Add(element);
}
Converting back is easy with LINQ:
List<string> list = collection.Cast<string>().ToList();
Use List.ToArray()
which will convert List to an Array which you can use to add values in your StringCollection
.
StringCollection sc = new StringCollection();
sc.AddRange(mylist.ToArray());
//use sc here.
Read this
Here's an extension method to convert an IEnumerable<string>
to a StringCollection
. It works the same way as the other 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;
}
}
我会比较喜欢:
Collection<string> collection = new Collection<string>(theList);
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.