简体   繁体   中英

Filtering a collection of objects by ID

Teaching myself some c# and my problem is that I have a class which creates Person objects and adds them to a List (myPersonList). I also have a PartyGroup class which takes a PersonList as one of its properties. My issue is that myPersonList contains the whole results set so at the moment each time it creates a new PartyGroup it adds all the values in myPersonList. Is there a way to tell it to only add those values in myPersonList where the Person.PartyGroupId matches the current PartyGroup groupID we are dealing with. Hope that makes sense. Thanks.

//Person

using (AseDataReader reader = commandPerson.ExecuteReader())

        {
            while (reader.Read())
            {
                Person person = new Person();
                person.PersonID = Convert.ToInt32(reader["person_id"]);
                person.PartyGroupID = Convert.ToInt32(reader["party_group_id"]);
                person.FullName = reader["full_name"].ToString();

                myPersonList.Add(person);
            }
        }

//PartyGroup

using (AseDataReader reader = commandPartyGroup.ExecuteReader())

        {
            while (reader.Read())
            {
                int groupId = Convert.ToInt32(reader["party_group_id"]);

                if (myPartyGroupList.Where(partyGroup => partyGroup.PartyGroupID == groupId).Any() == false) 
                {
                    PartyGroup partyGroup = new PartyGroup()
                    {
                        PartyGroupID = groupId,
                        PartyGroupName = reader["party_group_name"].ToString(),
                        PersonList = myPersonList//where PersonList objects contain this groupId???


                    };

                    myPartyGroupList.Add(partyGroup);

                }

            }

        }

如果我正确理解了您的问题,则只需要:

PersonList = myPersonList.Where(p => p.PartyGroupID == groupId).ToList();

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