简体   繁体   English

将字符串数组转换为C#中的字符串集合

[英]Convert a string array to collection of string in c#

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. 注意:我无法将Collection更改为ICollection。 It has to be Collection only. 它只能是Collection。

If the Collection is already created you can enumerate the items of the array and call Add 如果已经创建了Collection则可以枚举数组的项并调用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 否则,您可以从字符串数组初始化Collection

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

使用正确的ctor,传入数组:

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

You can give your string array by parameter to Collection<string> ctor, like here: 您可以按参数将字符串数组提供给Collection<string> ctor,如下所示:

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 . 关于Collection<T>您可以在这里阅读: https : //msdn.microsoft.com/ru-ru/library/ms132397(v=vs.110).aspx

For a clean solution, you could use the ForEach static method of Array like so: 对于一个干净的解决方案,您可以使用Array的ForEach静态方法,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM