1

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.

1
  • What problem? and why that note? Commented Dec 7, 2016 at 12:08

4 Answers 4

4

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);
Sign up to request clarification or add additional context in comments.

Comments

2

Use the correct ctor, passing in the array:

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

Comments

1

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.

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.