List <t>的动态类型?</t>

时间:2010-04-30 12:43:40

标签: c# list dynamic

我有一个返回DataSet表的List的方法

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

有没有办法可以动态设置列表的数据类型,并且这个方法适合所有数据类型,因此我可以在调用此方法时指定它应该是List<int&gt;还是List<string>List<AnythingILike>

此外,在声明方法时返回类型是什么?

提前致谢, 布雷特

2 个答案:

答案 0 :(得分:12)

使您的方法通用:

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

然后调用它:

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

答案 1 :(得分:3)

代码的通用版本:

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

如果您只需要一系列值,则可以避免创建临时表并使用枚举器:

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