[英]Instantiate a List inside of type initializer
Say I have a struct
like so 说我有一个像这样的struct
public struct MyStruct
{
string StructConfig { get; set; }
List<string> Details { get; set; }
public MyStruct
{
Details = new List<string>();
}
}
And I instantiate this struct
using: 我使用以下方法实例化此struct
:
MyStruct s = new MyStruct()
{
StructConfig = "Some config details"
}
I'm wondering how I could add a foreach
loop that will add the details into the Details
property, rather than doing: 我想知道如何添加一个foreach
循环,该循环会将详细信息添加到Details
属性中,而不是这样做:
MyStruct s = new MyStruct()
{
StructConfig = "Some config details"
}
s.Details = new List<string>();
foreach (var detail in someArray)
s.Details.Add(detail);
Is this even possible? 这有可能吗? Am I dreaming of code-luxury? 我是否梦想着代码奢侈?
You can do it like this: 您可以这样做:
MyStruct s = new MyStruct()
{
StructConfig = "Some config details",
Details = new List<string>(someArray)
}
This works because List<T>
supports initialization from IEnumerable<T>
through this constructor . 之所以List<T>
是因为List<T>
支持通过此构造方法从IEnumerable<T>
进行初始化。
If you need to do additional preparations on the elements of someArray
, you could use LINQ and add a Select
. 如果需要对someArray
的元素进行其他准备,则可以使用LINQ并添加Select
。 The example below adds single quotes around each element: 下面的示例在每个元素周围添加单引号:
Details = new List<string>(someArray.Select(s => string.Format("'{0}'", s)))
怎么样?
s.Details = new List<string>(someArray);
Assuming that you don't want to initialize the list from an array but really want to be able to write the list elements directly in your initializer you can use a collection initializer : 假设您不想从数组初始化列表,但确实希望能够直接在初始化程序中写入列表元素,则可以使用集合初始化程序 :
var myStruct = new MyStruct() {
StructConfig = "Some config details",
Details = new List<string>() { "a", "b", "c" }
};
Now, having a struct containing a string and a list of strings looks slightly weird but that doesn't affect how to answer the question. 现在,拥有包含字符串和字符串列表的结构看起来有些奇怪,但这并不影响如何回答问题。
can do something like this 可以做这样的事情
MyStruct s = new MyStruct
{
StructConfig = "Some config details",
Details = someArray.ToList()
};
You could call the extension method ToList() on the "someArray" collection, which will create a copy of it that you could assign to your struct property, like so: 您可以在“ someArray”集合上调用扩展方法ToList(),这将创建它的副本,您可以将其分配给struct属性,如下所示:
MyStruct s = new MyStruct()
{
StructConfig = "Some config details",
Details = someArray.ToList()
}
Something along the lines of: 类似于以下内容:
s.Details = someArray.Select(detail=> detail.ToString()).ToList()
Would prevent an exception being thrown were your array not a string[]. 如果您的数组不是字符串[],将防止引发异常。 Of course, you may wish for the exception to be thrown in this case. 当然,您可能希望在这种情况下引发异常。
Also, it's worth considering why you are using a struct with a property that is a List; 另外,值得考虑为什么要使用具有List属性的结构。 it may be better to have a class instead of a struct. 最好有一个类而不是一个结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.