简体   繁体   中英

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.

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

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 .Add ing 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.

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
}

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