2010-04-30 9 views
7

Tengo un método que devuelve una lista de una mesa conjunto de datosTipo dinámico para la lista <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; 
    } 

¿Hay alguna manera de ajustar dinámicamente el tipo de datos para la lista y tener este método de atender a todos los tipos de datos para que pueda especificar, previa llamando a este método que debe ser List<int> o List<string> o List<AnythingILike>?

Además, ¿cuál sería el tipo de devolución al declarar el método?

Gracias de antemano, Brett

Respuesta

11

Haga su método genérico:

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; 
} 

Entonces llamarlo:

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

Demasiado simple, gracias! – Brett

3

una versión genérica de su código:

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]); 
} 

Si solo necesita una secuencia de valores, puede evitar crear la tabla temporal y usar un enumerador:

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