Reputation: 457
I'm facing a problem in my code, where I have properties of two different models whose type cannot be changed by me. One is a string array and one is a collection of string. Now I need to add all the elements in the string array to the collection. I'm providing a sample code below.
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*/);
Note: I cannot change the Collection to ICollection. It has to be Collection only.
Upvotes: 0
Views: 10485
Reputation: 449
For a clean solution, you could use the ForEach static method of Array like so:
Collection<string> collection = new Collection<string>();
string[] arraystring = new string[] { "Now", "Today", "Tomorrow" };
Array.ForEach(arraystring, str => collection.Add(str));
Upvotes: 1
Reputation: 823
You can give your string array by parameter to Collection<string>
ctor, like here:
var collection = new Collection<string>(new[] { "Now", "Today", "Tomorrow" });
About Collection<T>
you can read here: https://msdn.microsoft.com/ru-ru/library/ms132397(v=vs.110).aspx.
Upvotes: 1
Reputation: 175826
Use the correct ctor, passing in the array:
Collection<string> collection = new Collection<string>(arraystring);
Upvotes: 2
Reputation: 136124
If the Collection
is already created you can enumerate the items of the array and call Add
Collection<string> collection = new Collection<string>();
string[] arraystring = new string[]{"Now","Today","Tomorrow"};
foreach(var s in arrayString)
collection.Add(s);
Otherwise you can initialize a Collection
from an array of strings
string[] arraystring = new string[]{"Now","Today","Tomorrow"};
Collection<string> collection = new Collection<string>(arraystring);
Upvotes: 3