Huma Ali
Huma Ali

Reputation: 1809

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?

Upvotes: 0

Views: 279

Answers (3)

Chris Pickford
Chris Pickford

Reputation: 8991

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

Upvotes: 1

Victor Leontyev
Victor Leontyev

Reputation: 8736

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

Upvotes: 1

TheJP
TheJP

Reputation: 114

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 = ...

Upvotes: 2

Related Questions