2009-01-26 8 views
0

J'ai cette classe.Pourquoi un élément d'une liste générique ne sera-t-il pas supprimé à l'aide de la méthode Supprimé?

public class Foo 
{ 
    public Guid Id { get; set; } 

    public override bool Equals(object obj) 
    { 
     Foo otherObj = obj as Foo; 

     return otherObj == null && otherObj.Id == this.Id; 
    } 

    public override int GetHashCode() 
    { 
     return this.Id.GetHashCode(); 
    } 
} 

Vous pouvez voir que j'ai outrepassé les valeurs Equals et GetHashCode pour cet objet.

Maintenant, je lance l'extrait de code suivant

// Create Foo List 
List<Foo> fooList = new List<Foo>(); 

fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 
fooList.Add(new Foo { Id = Guid.NewGuid()}); 

// Keep Id of last Create 
Guid id = Guid.NewGuid(); 

fooList.Add(new Foo { Id = id }); 

Console.WriteLine("List Count {0}", fooList.Count); 

// Find Foo in List 
Foo findFoo = fooList 
    .Where<Foo>(item => item.Id == id) 
    .FirstOrDefault<Foo>(); 

if (findFoo != null) 
{ 
    Console.WriteLine("Found Foo"); 

    // Found Foo now I want to delete it from list 
    fooList.Remove(findFoo); 
} 

Console.WriteLine("List Count {0}", fooList.Count); 

Lorsque cela est exécuté foo se trouve, mais la liste ne supprime pas l'élément trouvé.

Pourquoi est-ce? Je pensais que remplacer les Equals et GetHashCode devrait résoudre ce problème?

Répondre

8
return otherObj == null && otherObj.Id == this.Id; 

Est-ce correct? Ne devrait-il pas être

return otherObj != null && otherObj.Id == this.Id; 
+0

C'est exactement l'erreur. Merci beaucoup. Erreur muette. –

+0

:) Ça nous arrive à tous ... – BFree

+0

"Aw, on dirait que quelqu'un a un cas des lundis!" - Mimi, espace de bureau – Powerlord