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?
Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 .
To create a list with a single item repeated N times with Python, we can use the * operator with a list and the number of items to repeat. We define my_list by using an list and 10 as an operand to return a list with 'foo' repeated 10 times.
You can use Repeat
:
List<int> listFullOfInts = Enumerable.Repeat(42, 50).ToList();
Demo
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();
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With