简体   繁体   中英

Convert list to int array in C#

I have searched through StackOverflow and Google for the conversion, but unfortunately I was unable to get the solution. Everything was the opposite of what I wanted. ie, Conversion of an int[] to List .

Problem

I have this code in my [WebMethod] .

[WebMethod]
public int MyMethodWS(int N, List<int> M)
{
}

And now I have a Console Application , that references this service by using this URL:

http://localhost:61090/MyMethod.asmx?WSDL

I have this code in my Console Application:

int N;
List<int> M = new List<int>();
// Some crazy user input coding.
// Ultimately you will have non-empty M list and N int.
MyMethod.MyMethodWS DA = new MyMethod.MyMethodWS();
Sum = DA.MyMethodWS(N, M);

When I run this code, I am getting this error:

#1: The best overloaded method match for ' MyMethod.MyMethod.MyMethodWS(int, int[]) ' has some invalid arguments.

#2: Argument 2: cannot convert from ' System.Collections.Generic.List<int> ' to ' int[] '

Questions

  1. I have used only List there. But why is it trying to convert as int[] ?
  2. Currently the WebService as well as Console Application, both run in the same Solution. Is it a problem? Should I use different solutions, or different instances of Visual Studio 2012 altogether?

It is trying to convert it to int[] , because MyMethodWS takes a int[] as a parameter, instead of List<int> that you are trying to pass it. To convert a List<int> to int[] , call List<T>.ToArray();

So change the line Sum = DA.MyMethodWS(N, M); to Sum = DA.MyMethodWS(N, M.ToArray());

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