我有一个方法返回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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法可以动态设置列表的数据类型,并且这个方法适合所有数据类型,所以我可以在调用此方法时指定它应该是List<int> List<string>或者List<AnythingILike>?
另外,在声明方法时返回类型是什么?
先谢谢,布雷特
Dan*_*ert 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;
}
Run Code Online (Sandbox Code Playgroud)
然后叫它:
List<string> test1 = GetListFromDataTable<string>(dataSet, tableName, rowName);
List<int> test2 = GetListFromDataTable<int>(dataSet, tableName, rowName);
List<Guid> test3 = GetListFromDataTable<Guid>(dataSet, tableName, rowName);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3176 次 |
| 最近记录: |