开发者

Dynamic type for List<T>?

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 a开发者_JS百科ll 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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜