How can I get a new array from the second element forward in C #?

I initially had this code, which, as I mistakenly thought, would do what I wanted:

string firstArg = args[0];
string[] otherArgs = args.Except(new string[] { args[0] }).ToArray();

However, the .Except method seems to remove duplicates. Therefore, if I were to go through the arguments a b c c, the result otherArgswould be b cnot b c c.

So how can I get a new array with all the elements of the second element?

+3
source share
4 answers

Use the method Skip:

var otherArgs = args.Skip(1).ToArray();
+7
source

If you do not have a target array:

string[] otherArgs = args.Skip(1).ToArray();

If you do:

Array.Copy(args, 1, otherArgs, 0, args.Length - 1);
+3
source

linq, , :

string[] otherArgs = args.skip(1).ToArray();
+2

You can also use the ConstrainedCopy method . Here is a sample code:

static void Main(string[] args)
{
    string firstArg = args[0];
    Array otherArgs = new string[args.Length - 1];
    Array.ConstrainedCopy(args, 1, otherArgs, 0, args.Length - 1);

    foreach (string foo in otherArgs)
    {
        Console.WriteLine(foo);
    }
}

}

+2
source

Source: https://habr.com/ru/post/1724454/


All Articles