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 开发者_StackOverflow= 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);
}
}
}
If I understand your problem correctly, you just need:
PersonList = myPersonList.Where(p => p.PartyGroupID == groupId).ToList();
精彩评论