vexe
vexe

Reputation: 5615

Concat arrays at a certain index with LINQ?

I want to do this in LINQ:

public static void ConcatAt(this string[] items, string[] others, int at)
{
    for (int i = 0; i < others.Length && at < items.Length; i++, at++) {
        items[at] = others[i];
    }
}

Usage:

string[] groups = { "G1", "G2", "G3" };
string[] names = new string[groups.Length + 1];
names[0] = "Choose";
names.ConcatAt(groups, 1);

foreach (var n in names)
    Console.WriteLine(n);

/*
Choose
G1
G2
G3
*/

String was just an example, could be anything though.

So is there a LINQ method that does this?

Doing a names = names.Concat(groups).ToArray(); will include the empty strings that's in names so if I print names I'd get:

/*
Choose



G1
G2
G3
*/

Thanks.

Upvotes: 1

Views: 1590

Answers (2)

Binson Eldhose
Binson Eldhose

Reputation: 749

I think it will work for you

         string[] groups = { "G1", "G2", "G3" };

        var myNewItems = groups.ToList();

        int pos = 1;
        string value = "Choose";
        myNewItems.Insert(pos,value);



        foreach (var v in myNewItems)
        {
            Console.WriteLine(v);
        }
        Console.ReadLine();

Upvotes: 1

Victor Mukherjee
Victor Mukherjee

Reputation: 11025

Why are you not using Array.Copy?

Array.Copy(groups, 0, names, at,groups.Length);

Upvotes: 5

Related Questions