代码之家  ›  专栏  ›  技术社区  ›  Damovisa

如何从c#中的第二项开始获取新数组?

  •  3
  • Damovisa  · 技术社区  · 16 年前

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

    但是,.Except方法似乎删除了重复项。所以如果我要通过辩论 a b c c ,结果 otherArgs 会是 b c b c c .

    那么,如何获得一个包含从第二个元素开始的所有元素的新数组呢?

    4 回复  |  直到 16 年前
        1
  •  7
  •   SLaks    16 年前

    使用 Skip 方法:

    var otherArgs = args.Skip(1).ToArray();
    
        2
  •  3
  •   jason    16 年前

    如果您心中没有指定数组:

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

    如果您这样做:

    Array.Copy(args, 1, otherArgs, 0, args.Length - 1);
    
        3
  •  2
  •   Michael Gattuso    16 年前

    在我的脑海中使用linq,就像你现在的样子:

    string[] otherArgs = args.skip(1).ToArray();
    
        4
  •  2
  •   nithins    16 年前

    ConstrainedCopy 方法。下面是一些示例代码:

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

    }