Reputation: 48537
Say I have a struct
like so
public struct MyStruct
{
string StructConfig { get; set; }
List<string> Details { get; set; }
public MyStruct
{
Details = new List<string>();
}
}
And I instantiate this struct
using:
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:
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?
Upvotes: 2
Views: 126
Reputation: 726479
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.
If you need to do additional preparations on the elements of someArray
, you could use LINQ and add a Select
. The example below adds single quotes around each element:
Details = new List<string>(someArray.Select(s => string.Format("'{0}'", s)))
Upvotes: 2
Reputation: 3689
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; it may be better to have a class instead of a struct.
Upvotes: 0
Reputation: 572
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:
MyStruct s = new MyStruct()
{
StructConfig = "Some config details",
Details = someArray.ToList()
}
Upvotes: 0
Reputation: 106806
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.
Upvotes: 1
Reputation: 768
can do something like this
MyStruct s = new MyStruct
{
StructConfig = "Some config details",
Details = someArray.ToList()
};
Upvotes: 0