我需要上述功能,因为我只能将StringCollection存储到设置中,而无法存储字符串列表。
如何将列表转换为StringCollection?
如何尝试:
StringCollection collection = new StringCollection();
collection.AddRange(list.ToArray());
另一种避免中间数组的方法(但可能涉及更多的重新分配):
StringCollection collection = new StringCollection();
foreach (string element in list)
{
collection.Add(element);
}
LINQ 简化了转换回去的过程:
List<string> list = collection.Cast<string>().ToList();
List.ToArray()
将 List 转换为数组,您可以使用该数组将值添加到您的 StringCollection
中。StringCollection sc = new StringCollection();
sc.AddRange(mylist.ToArray());
//use sc here.
阅读 这篇文章。
string[] str = mylist.ToArray();
,而不是直接写 sc.AddRange(mylist.ToArray());
呢? - dtsgmylist.ToArray()
会返回什么,以及 AddRange()
接受什么参数。 - Nikhil Agrawal.ToArray();
难道不是很明显吗? - dtsgIEnumerable<string>
转换为 StringCollection
。它的工作方式与其他答案相同,只是进行了包装。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);