2012-03-08 22 views
16

Ho provato un paio di modi diversi e non riesco a ottenere il risultato che voglio usando vb.net.Converte array di stringhe nell'array int

Ho una matrice di stringhe. { "55555", "44444", " "}

ho bisogno di un array di interi {} 55555,44444

Questa è una pagina WPF che sta inviando la matrice come parametro per un rapporto di cristallo.

Qualsiasi aiuto è apprezzato.

risposta

34

È possibile utilizzare il metodo List(Of T).ConvertAll:

Dim stringList = {"123", "456", "789"}.ToList 
Dim intList = stringList.ConvertAll(Function(str) Int32.Parse(str)) 

o con il delegato

Dim intList = stringList.ConvertAll(AddressOf Int32.Parse) 

Se si desidera utilizzare solo Array, si possibile utilizzare il Array.ConvertAll method:

Dim stringArray = {"123", "456", "789"} 
Dim intArray = Array.ConvertAll(stringArray, Function(str) Int32.Parse(str)) 

Oh, ho perso la stringa vuota nei dati di esempio. Allora avete bisogno di controllare questo:

Dim value As Int32 
Dim intArray = (From str In stringArray 
       Let isInt = Int32.TryParse(str, value) 
       Where isInt 
       Select Int32.Parse(str)).ToArray 

A proposito, qui è la stessa sintassi metodo, brutta as always in VB.NET:

Dim intArray = Array.ConvertAll(stringArray, 
         Function(str) New With { 
          .IsInt = Int32.TryParse(str, value), 
          .Value = value 
         }).Where(Function(result) result.IsInt). 
       Select(Function(result) result.Value).ToArray 
+1

Non sono sicuro se è implicito, ma questo non copre il caso di una conversione fallita (stringa vuota). – vcsjones

+0

@vcsjones: hai ragione, ho perso la stringa vuota nei dati di esempio, ho modificato la mia risposta di conseguenza. –

+0

Penso che non sia brutto quando si gratifica il delegato di ConvertAll: 'Dim tempInt%: Dim intA As Int32() = intStrA.Where (Funzione (x) Int32.TryParse (x, tempInt)). Select (Function (x) tempInt) .ToArray() ' –

1

Forse qualcosa di simile:

dim ls as new List(of string)() 
ls.Add("55555") 
ls.Add("44444") 
ls.Add(" ") 
Dim temp as integer 
Dim ls2 as List(Of integer)=ls.Where(function(x) integer.TryParse(x,temp)).Select(function(x) temp).ToList() 
+0

Perché il voto verso il basso? – Arion

+0

Preferisco non passare dalla matrice di stringhe all'elenco di stringhe all'elenco di interi alla matrice di interi. Speravo di passare dall'array all'array. Lo metterà alla prova. Grazie. – Primetime

+0

Se l'intenzione è rimuovere elementi che non si convertono correttamente, allora è più efficiente utilizzare un elenco (di numero intero) quindi un array, poiché non si conosce la dimensione dell'array senza verificare se tutti loro può convertire prima. – vcsjones

4

È possibile utilizzare il metodo Array.ConvertAll:

Dim arrStrings() As String = {"55555", "44444"} 
    Dim arrIntegers() As Integer = Array.ConvertAll(arrStrings, New Converter(Of String, Integer)(AddressOf ConvertToInteger)) 


    Public Function ConvertToInteger(ByVal input As String) As Integer 
     Dim output As Integer = 0 

     Integer.TryParse(input, output) 

     Return output 
    End Function 
+0

...ti manca la stringa vuota nei dati di esempio dell'OP. –

1

Forse qualche altra riga di codice rispetto alle altre risposte, ma ...

'Example assumes the numbers you are working with are all Integers. 
    Dim arrNumeric() As Integer 

    For Each strItemInArray In YourArrayName 

     If IsNumeric(strItemInArray) Then 

      If arrNumeric Is Nothing Then 

       ReDim arrNumeric(0) 
       arrNumeric(0) = CInt(strItemInArray) 

      Else 

       ReDim Preserve arrNumeric(arrNumeric.Length) 
       arrNumeric(arrNumeric.Length - 1) = CInt(strItemInArray) 

      End If 

     End If 

    Next 
+1

Nota: 'CINT' genererà un' OverflowException' se il valore è numerico ma al di fuori dell'intervallo di un numero intero, perché ['IsNumeric'] (http://msdn.microsoft.com/en-us/library/6cd3f6w1 % 28VS.71% 29.aspx) restituisce anche 'true' per valori che sono nell'intervallo decimale. Lo stesso è vero se il valore contiene un '.' poiché questo potrebbe essere convertito in un doppio. –

+0

Quindi il commento di avviso all'inizio del blocco di codice, ma una buona spiegazione. – N0Alias

0

mio $ .02

Dim stringList() As String = New String() {"", "123", "456", "789", "a"} 
    Dim intList() As Integer 

    intList = (From str As String In stringList 
       Where Integer.TryParse(str, Nothing) 
       Select (Integer.Parse(str))).ToArray