Reputation: 1314
What I am trying to achieve is to add one item to a List, multiple times without using a loop.
I am going to add 50 numbers to a List and want all of those number to be equal to, let's say, 42. I am aware that I can simply create a small loop that runs 50 times and adds the same item over and over again, as such;
List<int> listFullOfInts = new List<int>();
int addThis = 42;
for(int i = 0; i < 50; i++)
listFullOfInts.Add(addThis);
What I am trying to do is something on the lines of;
listFullOfInts.AddRange(addThis, 50);
Or something that is similar to this at least, maybe using Linq? I have a vague memory of seeing how to do this but am unable to find it. Any ideas?
Upvotes: 37
Views: 41609
Reputation: 460208
You can use Repeat
:
List<int> listFullOfInts = Enumerable.Repeat(42, 50).ToList();
If you already have a list and you don't want to create a new one with ToList
:
listFullOfInts.AddRange(Enumerable.Repeat(42, 50));
If you want to do add reference types without repeating the same reference, you can use Enumerable.Range
+Select
:
List<SomeClass> itemList = Enumerable.Range(0, 50)
.Select(i => new SomeClass())
.ToList();
Upvotes: 67
Reputation: 21752
You can't do it directly with LINQ since LINQ is side effect free but you can use some of what's found in the System.linq namespace to build the required.
public static void AddRepeated<T>(this List<T> self,T item, int count){
var temp = Enumerable.Repeat(item,count);
self.AddRange(temp);
}
you can then use that as you propose in your post
listFullOfInts.AddRepeated(addThis, 50);
Upvotes: 5