Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add one item multiple times to same List

Tags:

c#

collections

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?

like image 772
Sander Avatar asked Jun 18 '13 12:06

Sander


People also ask

How do you add the same value to a list multiple times in Python?

Use the multiplication operator to create a list with the same value repeated N times in Python, e.g. my_list = ['abc'] * 3 .

How do I make a list of time in Python?

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.


2 Answers

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(); 
like image 185
Tim Schmelter Avatar answered Sep 21 '22 00:09

Tim Schmelter


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); 
like image 40
Rune FS Avatar answered Sep 24 '22 00:09

Rune FS