简体   繁体   中英

How to add object to list item in c#

I have following classes:

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; }
    }
}

I have QualifyResponse object which is populated with ProviderQualifyResponse but QuestionGroupList is empty. Now I want to fill QuestionGroupList . When I try to do it like this:

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

I get error:

System.Collections.Generic.List' does not contain a definition for 'QuestionGroupList' and no extension method 'QuestionGroupList' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)

How can I add a List<QuestionGroup> to my qualifyResponse.ProviderList ?

The error is this expression:

qualifyResponse.ProviderList.QuestionGroupList

ProviderList is of type List. You'll have to change it so you populate the correct item. Something like this:

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

Problem is that QuestionGroupList is property of class ProviderQualifyResponse and if you want to add List, you need to assign it to property of object. Example how to do that for all providers:

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

Given that qualifyResponse.ProviderList is of type List<ProviderQualifyResponse> , you are trying to access List.QuestionGroupList , which doesn't exist as the error states.

You'll either need to iterate through the instances in the list to access the instance properties, if that's your intention, or select an instance from the list you wish to instantiate.

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

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