如何在c#中将对象添加到列表项

时间:2017-01-31 11:33:39

标签: c# linq list object

我有以下课程:

public class QualifyResponse
{       
    List<ProviderQualifyResponse> _providerList = new List<ProviderQualifyResponse>();

    public List<ProviderQualifyResponse> ProviderList
    {
        get { return _providerList; }
        set { _providerList = value; }
    }
}

public class ProviderQualifyResponse
{
    private string _providerCode = string.Empty;

    public string ProviderCode
    {
        get { return _providerCode; }
        set { _providerCode = value; }
    }

    private List<QuestionGroup> _questionGroupList = new List<QuestionGroup>();

    public List<QuestionGroup> QuestionGroupList
    {
        get { return _questionGroupList; }
        set { _questionGroupList = value; }
    }
}

我有QualifyResponse对象,其中填充了ProviderQualifyResponse,但QuestionGroupList为空。现在我要填写QuestionGroupList。当我尝试这样做时:

QualifyResponse qualifyResponse = response;
qualifyResponse.ProviderList.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();

我收到错误:

  

System.Collections.Generic.List&#39;才不是   包含&#39; QuestionGroupList&#39;的定义没有扩展方法   &#39; QuestionGroupList&#39;接受第一个类型的参数   &#39; System.Collections.Generic.List&#39;可能   发现(您是否缺少using指令或程序集引用?)

如何向List<QuestionGroup>添加qualifyResponse.ProviderList

3 个答案:

答案 0 :(得分:2)

错误就是这个表达式:

qualifyResponse.ProviderList.QuestionGroupList

ProviderList的类型为List。您必须更改它才能填充正确的项目。像这样:

int index = ...;
qualifyResponse.ProviderList[index].QuestionGroupList = ...

答案 1 :(得分:1)

问题是QuestionGroupList是类ProviderQualifyResponse的属性,如果要添加List,则需要将其分配给object的属性。 示例如何为所有提供者执行此操作:

QualifyResponse qualifyResponse = response;
foreach(var provider in qualifyResponse.ProviderList)
{
     provider.QuestionGroupList = new List<DataTypes.BuyFlow.Entities.QuestionGroup>();
}

答案 2 :(得分:1)

鉴于<span id="table1"> </span> <table border="1"> <tbody><tr> <td>TD #0</td> <td>TD #1</td> <td>TD #2</td> </tr> <tr> <td>TD #3</td> <td>TD #4</td> <td>TD #5</td> </tr> <tr> <td>TD #6</td> <td>TD #7</td> <td>TD #8</td> </tr> </tbody></table> 属于qualifyResponse.ProviderList类型,您正在尝试访问List<ProviderQualifyResponse>,这不会作为错误状态存在。

您需要遍历列表中的实例以访问实例属性(如果这是您的意图),或者从您希望实例化的列表中选择一个实例。

List.QuestionGroupList