将DataSet转换为List

这是我的C#代码

Employee objEmp = new Employee(); List<Employee> empList = new List<Employee>(); foreach (DataRow dr in ds.Tables[0].Rows) { empList.Add(new Employee { Name = Convert.ToString(dr["Name"]), Age = Convert.ToInt32(dr["Age"]) }); } 

它使用循环来创build一个数据集列表。是否有任何直接的方法或更短的方法或一行代码转换数据集列表

尝试这样的事情:

 var empList = ds.Tables[0].AsEnumerable().Select(dataRow => new Employee{Name = dataRow.Field<string>("Name")}).ToList(); 

这里是将DataTable转换为对象列表的扩展方法:

  public static class Extensions { public static List<T> ToList<T>(this DataTable table) where T : new() { IList<PropertyInfo> properties = typeof(T).GetProperties().ToList(); List<T> result = new List<T>(); foreach (var row in table.Rows) { var item = CreateItemFromRow<T>((DataRow)row, properties); result.Add(item); } return result; } private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new() { T item = new T(); foreach (var property in properties) { if (property.PropertyType == typeof(System.DayOfWeek)) { DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString()); property.SetValue(item,day,null); } else { if(row[property.Name] == DBNull.Value) property.SetValue(item, null, null); else property.SetValue(item, row[property.Name], null); } } return item; } } 

用法:

 List<Employee> lst = ds.Tables[0].ToList<Employee>(); 

@ itay.b代码解释:我们首先使用reflection从类T中读取所有的属性名称
然后遍历数据表中的所有行并创buildT的新对象,
然后我们使用reflection来设置新创build的对象的属性。

属性值是从行的匹配列单元格中选取的。

PS:类属性名称和表列名称必须相同

 var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee { Name = r.Field<string>("Name"), Age = r.Field<int>("Age") }); var list = myData.ToList(); // For if you really need a List and not IEnumerable 

试试这个….根据你的需要修改代码。

  List<Employee> target = dt.AsEnumerable() .Select(row => new Employee { Name = row.Field<string?>(0).GetValueOrDefault(), Age= row.Field<int>(1) }).ToList(); 

用存储的proc命令填充数据集

 DbDataAdapter adapter = DbProviderFactories.GetFactory(cmd.Connection).CreateDataAdapter(); adapter.SelectCommand = cmd; DataSet ds = new DataSet(); adapter.Fill(ds); 

获取架构,

 string s = ds.GetXmlSchema(); 

保存到一个文件说:datasetSchema.xsd。 为Schema生成C#类:(在VS命令提示符下)

 xsd datasetSchema.xsd /c 

现在,当您需要将DataSet数据转换为类时,您可以反序列化(给生成的根类的默认名称是NewDataSet):

 public static T Create<T>(string xml) { XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StringReader reader = new StringReader(xml)) { T t = (T)serializer.Deserialize(reader); reader.Close(); return t; } } var xml = ds.GetXml(); var dataSetObjects = Create<NewDataSet>(xml); 
  DataSet ds = new DataSet(); ds = obj.getXmlData();// get the multiple table in dataset. Employee objEmp = new Employee ();// create the object of class Employee List<Employee > empList = new List<Employee >(); int table = Convert.ToInt32(ds.Tables.Count);// count the number of table in dataset for (int i = 1; i < table; i++)// set the table value in list one by one { foreach (DataRow dr in ds.Tables[i].Rows) { empList.Add(new Employee { Title1 = Convert.ToString(dr["Title"]), Hosting1 = Convert.ToString(dr["Hosting"]), Startdate1 = Convert.ToString(dr["Startdate"]), ExpDate1 = Convert.ToString(dr["ExpDate"]) }); } } dataGridView1.DataSource = empList; 

在这里输入图像说明

添加一个名为“Helper”的新类,并将该类的属性更改为“public static”

 public static class Helper { public static List<T> DataTableToList<T>(this DataTable table) where T : class, new() { try { List<T> list = new List<T>(); foreach (var row in table.AsEnumerable()) { T obj = new T(); foreach (var prop in obj.GetType().GetProperties()) { try { PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name); propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null); } catch { continue; } } list.Add(obj); } return list; } catch { return null; } } } 

并在后面的代码中访问这个类,如下所示

  DataTable dtt = dsCallList.Tables[0]; List<CallAssignment> lstCallAssignement = dtt.DataTableToList<CallAssignment>(); 

使用下面的代码:

 using Newtonsoft.Json; string JSONString = string.Empty; JSONString = JsonConvert.SerializeObject(ds.Tables[0]); 

尝试上面的任何列表types将运行。

  public DataTable ListToDataTable<T>(IList<T> data) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } object[] values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; }