2008-11-28 19 views
8

TuttiUso List.Exists e predicati correttamente

Attualmente sto cercando implementare qualcosa sulla falsariga di

dim l_stuff as List(of Stuff) 

dim m_stuff as new Stuff 

m_stuff.property1 = 1 
m_stuff.property2 = "This" 

if not l_stuff.exists(m_stuff) then 
    l_stuff.add(m_stuff) 
end if 

questo viene a mancare, ovviamente, come il metodo Exist è alla ricerca di un predicato di roba.

Qualcuno può spiegare completamente il predicato e come posso ottenere ciò che sto cercando di fare qui.

Ho provato ad utilizzare

if not l_stuff.contains(m_stuff) then 
    l_stuff.add(m_stuff) 
end if 

tuttavia questo non rileva l'entrata idenitcal ed entra un duplicato nella lista

Grazie

risposta

20

List(Of T).Contains è il metodo che si dovrebbe usare. Esiste, come dici tu, si aspetta un predicato. Ovviamente, per .Contains funziona come previsto, è necessario eseguire l'override del metodo Equals() e GetHashCode().

List(Of T).Exists prevede una funzione che restituirà un valore booleano quando viene passato un elemento di tipo T, dove T, nel tuo caso, è di tipo Stuff. Quindi, potresti scrivere un metodo che assomiglia a:

If Not l_stuff.Exists(Function(x) x.property1 = m_stuff.property1 And _ 
x.property2 = m_stuff.property2) Then 

e così via.

+1

+ 1 Ben spiegato. –

Problemi correlati