Gonzalo
Gonzalo

Reputation: 160

Add object to ICollection and then Add ICollection to a List<> ASP.NET

I'm not sure if this is possible or even makes total sense, but I need to add an object let's call it Person to an ICollection List People and add the collection to a List<> , in order to have the collection of people in a List<> that also will contain other parameters. I am not sure how to do this but I can show you what I have sketched so far.

    public void addPeopleToList(string PersonId)
    {
        Person p = findPerson(PersonId); /*Method that takes the ID and 
                                           returns an object from another List*/ 
        ICollection<People> ICollectionPeople; //Create the ICollection
        ICollectionPeople.Add(p);              //Add Person to Collection
        List.Add(ICollectionPeople);           //Add Collection to List
    }

If this way is not the proper way to do it, I am open to all other suggestions.

Upvotes: 1

Views: 3530

Answers (3)

async
async

Reputation: 1537

It's probably easier if you simply told us what exactly you want to achieve, but anyway:

  1. You need to assign a value to ICollectionPeople (also maybe it's worth renaming it and following the naming conventions). Maybe

    ICollection<People> peopleCollection = new List<People>();
    

Though do you really need that explicit type? You could use var.

  1. You need to create an instance of the list you want to add your collection of people to. Maybe

    var list = new List<People>();
    

Then finally, use AddRange() like

list.AddRange(peopleCollection);

Upvotes: 1

Rahul
Rahul

Reputation: 77936

Not sure but looks like you wanted to have a List<List<People>> .. if that's so then your code is missing initialization of the collection. You need to change a bit

public void addPeopleToList(string PersonId)
{
    Person p = findPerson(PersonId); /*Method that takes the ID and 
                                       returns an object from another List*/ 
    List<Person> ICollectionPeople = new List<Person>(); //Create the 
    ICollectionPeople.Add(p);              //Add Person to Collection
    List<List<Person>> personLists = new List<List<Person>>()
    personLists.Add(ICollectionPeople);           //Add Collection to List
}

Upvotes: 0

Sam Axe
Sam Axe

Reputation: 33738

I think what you need is another class.. like...

public class PersonWithAttributes : Person {
    // add attribute properties here
}

Then in your code above you would change List to be of type List<PersonWithAttributes> and instead of .Adding the collection you would call List.AddRange(ICollectionPeople). After which you would need to loop over the List items and add the extra attributes you were talking about.

Upvotes: 0

Related Questions