C#中获取DataTable某一列的值转换为集合
1、直接使用
List<int> lstID = (from d in dt.AsEnumerable() select d.Field<int>("ID")).ToList();
//使用orderby关键字进行排序
List<string> listJobTitle = (from d in dvBaseInfo.ToTable().AsEnumerable() orderby d.Field<int>("OrderNo") select d.Field<string>("VName")).ToList();
2、封装方法
/// <summary>
/// 获取某一列的所有值
/// </summary>
/// <typeparam name="T">列数据类型</typeparam>
/// <param name="dtSource">数据表</param>
/// <param name="filedName">列名</param>
/// <returns></returns>
public static List<T> GetColumnValues<T>(DataTable dtSource,string filedName)
{
return (from r in dtSource.AsEnumerable() select r.Field<T>("ID")).ToList<T>();
}
方法调用:
获取字段ID的所有值
DataTable dt = new DataTable();
List<int> ids= DataTablePro.GetColumnValues<int>(dt, "ID");