1

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.

3
  • Not sure I understand why, in your specific example, you can't use names = names.Concat(groups).ToArray();? Is the index a requirement .. ? Commented Jan 4, 2014 at 3:38
  • No because that would include the empty strings as well that's in names. So If I print names, I would get "Choose", "", "", "", G1", etc. Commented Jan 4, 2014 at 3:40
  • 2
    @vexe I don't know, it seems like a viable question to me. +1 Commented Jan 4, 2014 at 3:45

2 Answers 2

5

Why are you not using Array.Copy?

Array.Copy(groups, 0, names, at,groups.Length);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that works. I never used that. I thought there'd be some LINQ method.
1

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();

2 Comments

specific means? do you want to combine array in diffrent datata types?
I mean, I was looking for a more general solution that concatenates arrays from a certain index within a certain length but you provided a work-around that works specifically for my case where I just have to insert "Choose" before the "G"s. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.