2016-12-07 45 views
0

我在我的代碼中遇到了一個問題,其中有兩個不同模型的屬性,其類型不能由我更改。一個是字符串數組,另一個是字符串的集合。現在我需要將字符串數組中的所有元素添加到集合中。我在下面提供一個示例代碼。將字符串數組轉換爲c中字符串的集合#

Collection<string> collection = new Collection<string>(); 
string[] arraystring = new string[]{"Now","Today","Tomorrow"}; 
collection.Add(/*Here I need to give the elements of the above array*/); 

注意:我無法將Collection更改爲ICollection。它只能是集合。

+0

什麼問題?以及爲什麼這個筆記? – andy

回答

1

如果Collection已創建您可以枚舉數組的項目,並呼籲Add

Collection<string> collection = new Collection<string>(); 
string[] arraystring = new string[]{"Now","Today","Tomorrow"}; 
foreach(var s in arrayString) 
    collection.Add(s); 

否則,你可以從一個字符串數組

string[] arraystring = new string[]{"Now","Today","Tomorrow"}; 
Collection<string> collection = new Collection<string>(arraystring); 
2

使用正確的構造函數初始化Collection ,通過陣列:

Collection<string> collection = new Collection<string>(arraystring); 
1

對於一個乾淨的解決方案,你可以使用數組的給ForEach靜態方法,像這樣:

Collection<string> collection = new Collection<string>(); 
string[] arraystring = new string[] { "Now", "Today", "Tomorrow" }; 
Array.ForEach(arraystring, str => collection.Add(str)); 
相關問題