简体   繁体   English

将数组存储在数据协定中

[英]store array in data contract

i have a data contract defined as follows: 我有一个数据合同,定义如下:

[DataContract]
public class DemoSearchList : ReturnValuesBase
{
    [DataMember]
    public string SessionId { get; set; } 

    [DataMember]
    public string[] StartDate { get; set; }

    [DataMember]
    public string[] EndDate { get; set; }

    [DataMember]
    public string ProductID { get; set; }
}

as u can observe StartDate and Enddate are array of strings. 如您所见,StartDate和Enddate是字符串数组。 i want to send array of responses to these. 我想发送这些响应的数组。

for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
{
    DemoSearchList.StartDate[i] = Convert.ToString(DS.Tables[0].Rows[i][0]);
    DemoSearchList.EndDate[i] = Convert.ToString(DS.Tables[0].Rows[i][1]);
}

DS is a dataset. DS是数据集。 but i get an error as index out of bound . 但是我得到一个错误,因为索引超出范围。 can anyone please help and also tel me if anything extra needs to be declared and used to achieve this 任何人都可以请帮助,如果需要声明并使用其他任何电话来实现这一目标,请给我打电话

This means that your array is has not the correct size or is not yet initialized. 这意味着您的数组大小不正确或尚未初始化。 You need to do this before your for-loop: 您需要在for循环之前执行此操作:

DemoSearchList.StartDate = new string[DS.Tables[0].Rows.Count];
DemoSearchList.EndDate = new string[DS.Tables[0].Rows.Count];

But I would prefer to make a list instead of an array (if you don't need the index of each value): 但是我宁愿创建一个列表而不是一个数组(如果不需要每个值的索引):

[DataContract]
public class DemoSearchList : ReturnValuesBase
{
    public DemoSearchList()
    {
        this.StartDate = new List<string>();
        this.EndDate = new List<string>();
    }

    [DataMember]
    public List<string> StartDate { get; set; }

    [DataMember]
    public List<string> EndDate { get; set; }
}

Then your for-loop could look like this: 然后,您的for循环可能如下所示:

for (int i = 0; i < DS.Tables[0].Rows.Count; i++)
{
    DemoSearchList.StartDate.Add(Convert.ToString(DS.Tables[0].Rows[i][0]));
    DemoSearchList.EndDate.Add(Convert.ToString(DS.Tables[0].Rows[i][1]));
}

For using Array their length should be defined 对于使用Array length should be definedlength should be defined

StartDate = new String[10]; //can use data row count here
EndDate = new String[10]; //can use data row count here

if you want to use objects of dynamic length then use LIST instead 如果要使用objects of dynamic length则使用LIST代替

or change them to 或将它们更改为

[DataMember]
public List<String> StartDate { get; set; }

[DataMember]
 public List<String> EndDate { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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