posts - 315, comments - 268, trackbacks - 15

My Links

News

View Pietro Libro's profile on LinkedIn

DomusDotNet
   DomusDotNet

Pietro Libro

Tag Cloud

Article Categories

Archives

Post Categories

Blogs amici

Links

venerdì 27 novembre 2009

Estrazione di indici da una lista con LINQ

Se abbiamo una lista, ad esempio contenenti dei nomi, e vogliamo estrarre gli indici delle item che soddisfano una certa condizione di filtro, possiamo scrivere:

 1:  Dim Nomi As New List(Of String)
 2:   
 3:  Nomi.Add("Antonio")
 4:  Nomi.Add("Franco")
 5:  Nomi.Add("Giovanni")
 6:  Nomi.Add("Antonio")
 7:   
 8:  Dim sStringaRiferimento As String = "Antonio"
 9:   
10:  Dim q As IEnumerable(Of Integer) = Nomi.Select( _
11:  	Function(nome, indice) New With {nome, indice}) _
12:  	.Where(Function(item) item.nome.Equals(sStringaRiferimento)) _
13:  	.Select(Function(item) item.indice)

O meglio:

1:  Dim q1 = Nomi.Select(Function(v, i) RicercaNome(v, "Antonio", i)).Where(Function(i) i >= 0) 

Dove la funzione RicercaNome, è così definita:

1:  Private Function RicercaNome(ByVal a As String, ByVal b As String, ByVal c As Integer) As Integer
2:     If (a.Equals(b)) Then 
3:        Return c 
4:     Else 
5:        Return -1 
6:     End If 
7:  End Function

posted @ lunedì 1 gennaio 0001 00:00 | Feedback (0) | Filed Under [ LINQ ]

Powered by:
Powered By Subtext Powered By ASP.NET