Question

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.

Was it helpful?

Solution

Why are you not using Array.Copy?

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

OTHER TIPS

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();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top