2010-04-30 14 views
7

Ho un metodo che restituisce una lista per un tavolo DataSetTipo dinamico per l'elenco <T>?

public static List<string> GetListFromDataTable(DataSet dataSet, string tableName, string rowName) 
    { 
     int count = dataSet.Tables[tableName].Rows.Count; 
     List<string> values = new List<string>(); 

     // Loop through the table and row and add them into the array 
     for (int i = 0; i < count; i++) 
     { 
      values.Add(dataSet.Tables[tableName].Rows[i][rowName].ToString()); 
     } 
     return values; 
    } 

C'è un modo per impostare dinamicamente il tipo di dati per la lista e avere questo un metodo per tutti i tipi di dati di soddisfare in modo da poter specificare su chiamando questo metodo che dovrebbe essere un List<int> o List<string> o List<AnythingILike>?

Inoltre, quale sarebbe il tipo di ritorno quando si dichiara il metodo?

Grazie in anticipo, Brett

risposta

11

Fai il tuo metodo generico:

public static List<T> GetListFromDataTable<T>(DataSet dataSet, string tableName, string rowName) 
{ 
    // Find out how many rows are in your table and create an aray of that length 
    int count = dataSet.Tables[tableName].Rows.Count; 
    List<T> values = new List<T>(); 

    // Loop through the table and row and add them into the array 
    for (int i = 0; i < count; i++) 
    { 
     values.Add((T)dataSet.Tables[tableName].Rows[i][rowName]); 
    } 
    return values; 
} 

Poi chiamarlo:

List<string> test1 = GetListFromDataTable<string>(dataSet, tableName, rowName); 
List<int> test2 = GetListFromDataTable<int>(dataSet, tableName, rowName); 
List<Guid> test3 = GetListFromDataTable<Guid>(dataSet, tableName, rowName); 
+0

Troppo semplice, grazie! – Brett

3

Una versione generica del codice:

public List<T> GetListFromTable<T>(DataTable table, string colName) 
{ 
    var list = new List<T>(); 
    foreach (DataRow row in table) 
    { 
     list.Add((T)row[colName]); 
    } 
    return list; 
} 

public List<T> GetListFromDataTable<T>(DataSet ds, string tableName) 
{ 
    return GetListFromTable(ds.Tables[tableName]); 
} 

Se avete solo bisogno di una sequenza di valori, si può evitare di creare la tabella temporanea e utilizzare un enumeratore:

public IEnumerable<T> GetSequenceFromTable<T>(DataTable table, string colName) 
{ 
    foreach (DataRow row in table) 
    { 
     yield return (T)(row["colName"]); 
    } 
} 
Problemi correlati