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?
You can do it like this:
This works because
List<T>
supports initialization fromIEnumerable<T>
through this constructor.If you need to do additional preparations on the elements of
someArray
, you could use LINQ and add aSelect
. The example below adds single quotes around each element: