frenchie
frenchie

Reputation: 51947

adding to the beginning of lists in C#

I'm retuning a list of months from a function.

I'm looking to see if there's an elegant solution to adding 3 elements to the beginning of that list.

Thanks for your suggestions.

Upvotes: 0

Views: 240

Answers (4)

geofftnz
geofftnz

Reputation: 10092

Let's go crazy...

    // in a static class in a namespace you can see
    public static IEnumerable<T> Prepend<T>(this IEnumerable<T> second, IEnumerable<T> first)
    {
        foreach (var x in first)
        {
            yield return x;
        }
        foreach (var x in second)
        {
            yield return x;
        }
    }

    ...

    var newListOfMonths = listOfMonths.Prepend(someExtraItems).ToList();

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160922

You can use List.Insert() for that, it takes the index at which you want to add the new item, i.e. to add at the beginning:

list.Insert(0, item);

Also to add multiple items at the same time you can use List.InsertRange() which takes an IEnumerable as second parameter:

list.InsertRange(0, itemCollection);

Upvotes: 7

Andre Pena
Andre Pena

Reputation: 59336

List<int> listOfMonths = new List<int>();
// ... insert months here
listOfMonths.InsertRange(0, new int[] { 1, 2 ,3 });

Upvotes: 2

48klocs
48klocs

Reputation: 6103

You probably want InsertRange.

Upvotes: 3

Related Questions