0

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;
}
JamesSugrue
  • 14,891
  • 10
  • 61
  • 93
user3150422
  • 67
  • 1
  • 4

2 Answers2

2

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();
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
1

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.

Amy S
  • 31
  • 4
  • Thanks for your comments; I had already found that syntax, but there are numerous examples out there showing the form int[] s2 = args.ConvertAll (delegate converter ) ; is that deprecated now ? – user3150422 Apr 09 '15 at 15:28
  • Are you sure those examples weren't with lists, rather than arrays? That is the proper syntax for lists. See the difference in examples [here](https://msdn.microsoft.com/en-us/library/kt456a2y(v=vs.110).aspx). – Amy S Apr 09 '15 at 20:24
  • You're right, and that was my basic problem: I thought args was a list, when it was an array. Thanks! If I convert it to a list with: List list = args.OfType().ToList(); then I can sum it with int ss = list.ConvertAll(x => int.Parse(x)).Sum(); – user3150422 Apr 10 '15 at 01:58
  • Glad you got it figured out! – Amy S Apr 10 '15 at 06:09