Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic type for List<T>?

Tags:

c#

list

dynamic

I've got a method that returns a List for a DataSet table

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

Is there a way I can dynamically set the datatype for the list and have this one method cater for all datatypes so I can specify upon calling this method that it should be a List<int> or List<string> or List<AnythingILike>?

Also, what would the return type be when declaring the method?

Thanks in advance, Brett

like image 233
Brett Avatar asked Apr 30 '10 12:04

Brett


2 Answers

Make your method generic:

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

Then to call it:

List<string> test1 = GetListFromDataTable<string>(dataSet, tableName, rowName);
List<int> test2 = GetListFromDataTable<int>(dataSet, tableName, rowName);
List<Guid> test3 = GetListFromDataTable<Guid>(dataSet, tableName, rowName);
like image 51
Dan Herbert Avatar answered Sep 20 '22 12:09

Dan Herbert


A generic version of your code:

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

If you just need a sequence of values, you can avoid creating the temporary table and use an enumerator:

public IEnumerable<T> GetSequenceFromTable<T>(DataTable table, string colName)
{
    foreach (DataRow row in table)
    {
        yield return (T)(row["colName"]);
    }
}
like image 26
John Källén Avatar answered Sep 17 '22 12:09

John Källén