I have two lists A and B, at the beginning of my program, they are both filled with information from a database (List A = List B). My program runs, List A is used and modified, List B is left alone. After a while I reload List B with new information from the database, and then do a check with that against List A.
foreach (CPlayer player in ListA)
if (ListB.Contains(player))
-----
Firstly, the object player is created from a class, its main identifier is player.Name.
If the Name is the same, but the other variables are different, would the .Contains still return true?
Class CPlayer(
public CPlayer (string name)
_Name = name
At the —- I need to use the item from ListB that causes the .Contains to return true, how do I do that?
The default behaviour of
List.Containsis that it uses the default equality comparer. If your items are reference types this means that it will use an identity comparison unless your class provides another implementation viaEquals.If you are using .NET 3.5 then you can change your second line to this which will do what you want:
For .NET 2.0 you could implement
EqualsandGetHashCodefor your class, but this might give undesirable behaviour in other situations where you don’t want two player objects to compare equal if they have the same name but differ in other fields.An alternative way is to adapt Jon Skeet’s answer for .NET 2.0. Create a
Dictionary<string, object>and fill it with the names of all players in listB. Then to test if a player with a certain name is in listB you can usedict.ContainsKey(name).