![](/img/trans.png)
[英]Check if a list<StringCollection> contains list<string>
[英]Convert List<string> to StringCollection
我需要上述功能,因為我只能將StringCollection存儲到“設置”,而不是字符串列表。
一個如何將List轉換為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()
將列表轉換為一個數組,您可以使用該數組在StringCollection
添加值。
StringCollection sc = new StringCollection();
sc.AddRange(mylist.ToArray());
//use sc here.
讀這個
這是將IEnumerable<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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.