I am learning programming and my problem is that I have a bunch of objects and I want to add these objects to a list only if the list does not already contain that object. Secondly if the object is already contained I want to ignore that object and add the next one instead. I think I have got the first part working just need some help with part two. Many thanks.
PartyGroup partyGroup = new PartyGroup();
using (AseDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (!myPartyGroupList.Contains(partyGroup))
{
partyGroup.PartyGroupID = Convert.ToInt32(reader["party_group_id"]);
partyGroup.PartyGroupName = reader["party_group_name"].ToString();
partyGroup.PersonList = myPersonList;
myPartyGroupList.Add(partyGroup);
}
else
{
//??
}
}
}
When comparing it is better to use comparison with respect to a identifier, which in your case is the PartyGroupId. If you use contains then the default overload of Contains() then the hash value of the object in the list is used for comparison.
So rather than leave the comparison to .NET you can create a custom IEqualityComparer implementation or use Linq’s Where clause as follows.
Another suggestion is to rename to PartyGroup class members as: