简体   繁体   中英

C# ConvertAll syntax

I'm trying to understand the syntax for ConvertAll in C#, and despite looking at several examples and trying to copy them, I can't get the following line containing s2 to compile; VSE2013 says

"Error 1 No overload for method 'ConvertAll' takes 1 arguments ".

what does the error message mean? Where am I going wrong? And yes, I understand that Select is much better to use in these situations, for several reasons. Thanks!

static int Main(string[] args)
{ 
    Console.WriteLine ("jello world");

    int s1 = args.Sum(st => int.Parse(st));
    int s2 = args.ConvertAll(x => int.Parse(x)).Sum();
    int s3 = args.Select(st => int.Parse(st)).Take(2).Sum();
    return 0;
}

You are calling ConvertAll on an actual array instance - but ConvertAll is a static method, hence does not have access to the content of your array - you need to pass in the array itself as the first parameter so that it can use it - and since it's a static method should call it on the Array class itself:

int s2 = Array.ConvertAll(args, x => int.Parse(x)).Sum();

Also shorter using a method group:

int s2 = Array.ConvertAll(args, int.Parse).Sum();

Change args.ConvertAll(x => int.Parse(x)).Sum(); to Array.ConvertAll(args, x => int.Parse(x)).Sum(); .

As the error message told you, 'ConvertAll' does not take 1 argument, so that should clue you in to the fact that you need more arguments (in this case, the array).

See MSDN for proper usage of Array.ConvertAll.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM