Bonaca
Bonaca

Reputation: 313

How to duplicate list members in C#?

int x = 9; 
List<string> list = new List<string> {"a", "b"};

I want list to be: a b a b a ... until list.Count = x. How might I achieve this?

Upvotes: 1

Views: 255

Answers (4)

Shezi
Shezi

Reputation: 1342

int x = 9;
List<string> list = new List<string> {};

for (int i = 0; i < x; i++)
{
    list.Add("a");
    list.Add("b");    
}

// verify    
foreach (var item in list)
{
    Console.WriteLine(item);    
}

Upvotes: 0

Ani
Ani

Reputation: 113442

How about:

var result= Enumerable.Repeat(new[] { "a", "b" }, int.MaxValue)
                      .SelectMany(strArray => strArray)
                      .Take(x)
                      .ToList();

Upvotes: 3

Michal B.
Michal B.

Reputation: 5719

Something like this should work. I did not check it, let it be an exercise for you :)

int currentCount = list.Count;

for (int i=0; i<x; ++i)
{
     list.Add(list[i%currentCount]);  
}

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1501033

You could do it with LINQ easily:

List<string> result = (from ignored in Enumerable.Range(0, int.MaxValue)
                       from item in list
                       select item).Take(count).ToList();

Or without using a query expression:

List<string> result = Enumerable.Range(0, int.MaxValue)
                                .SelectMany(ignored => list)
                                .Take(count)
                                .ToList();

The use of Enumerable.Range here is just to force repetition - like Ani's approach of using Enumerable.Repeat, which will work too of course.

Upvotes: 4

Related Questions