Way to fill List<> with elements
I have in my code
List<BookedReelsState>开发者_如何学Python; retVal = new List<BookedReelsState>(somesize);
Match later in the code if some condition works I need to fill this entire List with same value.
Of course I can do it via foreach
loop and set values , Is there more elegant way to do so ?
I just to learn something new here .
retVal.AddRange(Enumerable.Repeat(value, somesize));
retVal.ForEach(b => b.changedProp = newValue);
Two things here.
Firstly List<T>(int capacity)
does not create a List with capacity
items in it already. It just reserves memory for them. So the list in the example above will have it's length equals to 0.
But if you have a list and want to set each element of it, you can do it like this:
retVal.ForEach( rv => rv = desiredValue );
Where desiredValue is the value you want to set for each element.
I also find it strange that you want to fill every single element of a list with the same value. If all elements are the same the list serves no purpose, but I guess that you might need to fill with some default value up front, and then change some of them later on.
If you have an IEnumerable then you can use List.AddRange.
Example:
var list = new List<BookedReelsState>(20);
var someEnumerable = new []
{
new BookedReelsState(1),
new BookedReelsState(2),
new BookedReelsState(2)
};
list.AddRange(someEnumerable);
精彩评论