2

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?

6 Answers 6

2

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

1 Comment

I think you need to remove the ; as that will give an excpetion.
1

How about?

s.Details = new List<string>(someArray); 

Comments

1

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.

Comments

0

can do something like this

MyStruct s = new MyStruct { StructConfig = "Some config details", Details = someArray.ToList() }; 

Comments

0

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() } 

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.