Is there any difference between using Arrays or converting a list to an Array in C# when sending to a web service method?

时间:2022-12-13 22:28:22

This question may be similar to already answered once, but my question is about sending either Array or List.ToArray() to the web service's method when it accepts Array of Objects.

这个问题可能类似于已经回答过一次,但我的问题是当它接受对象数组时,将Array或List.ToArray()发送到Web服务的方法。

So, here is the question:

所以,这是一个问题:

I need to send Array of Programs to a web service.

我需要将一组程序发送到Web服务。

By service definition, the Main Object, that I need to send to a web service has the following wsdl type:

通过服务定义,我需要发送到Web服务的主对象具有以下wsdl类型:

<xsd:element name="Pgms" type="ns1:ArrayOfPrograms" nillable="true" minOccurs="0"/>

Is there any difference between the following codes:

以下代码之间是否有任何区别:

1st Option:

List<string> programList = insertRow["programName"].ToString().Trim().Split(',').ToList();
Program [] programArray = new Program[programList.Count];
foreach(var program in programList)
{
      Program programObj = new Program();
      programObj.Item1 = item1;
      programObj.Item2 = program.ToString().Trim();
      for(int i = 0; i <= programList.Count; i++)
      { 
          programArray[i] = programObj;
      }
}

webserviceMethod.send(mainObject);

2nd Option:

List<string> programList = insertRow["programName"].ToString().Trim().Split(',').ToList();
List<Program> programList = new List<Program>();
foreach(var program in programList)
{
     Program programObj = new Program();
     programObj.Item1 = item1;
     programObj.Item2 = program.ToString().Trim();
     programList.Add(programObj);
}
programList.ToArray();
webserviceMethos.send(mainObject);

Which option do I need to use to send to the service?

我需要使用哪个选项发送到服务?

1 个解决方案

#1


2  

A List is backed by an array. Populating an array T[] by looping through a list or calling ToArray() on a List<T> will result in the same thing an object T[] at the end.

List由数组支持。通过循环遍历列表或在List 上调用ToArray()来填充数组T []将导致最后一个对象T []。

Personally I prefer adding items to a list then calling to array but either method will work.

我个人更喜欢将项目添加到列表然后调用数组,但任何一种方法都可以。

There are however multiple issues with both of the examples you provide which may actually be where the issues lie, not in which method will yield an array to send to a web service.

但是,您提供的两个示例都存在多个问题,这些问题实际上可能是问题所在,而不是哪个方法会产生要发送到Web服务的数组。

#1


2  

A List is backed by an array. Populating an array T[] by looping through a list or calling ToArray() on a List<T> will result in the same thing an object T[] at the end.

List由数组支持。通过循环遍历列表或在List 上调用ToArray()来填充数组T []将导致最后一个对象T []。

Personally I prefer adding items to a list then calling to array but either method will work.

我个人更喜欢将项目添加到列表然后调用数组,但任何一种方法都可以。

There are however multiple issues with both of the examples you provide which may actually be where the issues lie, not in which method will yield an array to send to a web service.

但是,您提供的两个示例都存在多个问题,这些问题实际上可能是问题所在,而不是哪个方法会产生要发送到Web服务的数组。