将DataTable
转换成List
是C#开发中常见的需求,下面是将DataTable
转换成List
的完整攻略。
步骤1:创建实体类
创建一个实体类作为转换后的对象类型。实体类中的属性需要与DataTable
中的列对应。
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
步骤2:将DataTable转换成List
可以使用LINQ或者foreach循环遍历DataTable
并将每一行转换成实体类。
方法一:使用LINQ
List<Person> personList = dataTable.AsEnumerable().Select(row => new Person
{
Id = row.Field<int>("Id"),
Name = row.Field<string>("Name"),
Age = row.Field<int>("Age")
}).ToList();
方法二:使用foreach循环
List<Person> personList = new List<Person>();
foreach (DataRow row in dataTable.Rows)
{
Person person = new Person
{
Id = Convert.ToInt32(row["Id"]),
Name = row["Name"].ToString(),
Age = Convert.ToInt32(row["Age"])
};
personList.Add(person);
}
示例一:从数据库中读取数据转换成List
using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=TestDB;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Persons", conn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
List<Person> personList = dataTable.AsEnumerable().Select(row => new Person
{
Id = row.Field<int>("Id"),
Name = row.Field<string>("Name"),
Age = row.Field<int>("Age")
}).ToList();
}
示例二:从CSV文件中读取数据转换成List
using (var reader = new StreamReader("path/to/csv/file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
var records = csv.GetRecords<dynamic>();
DataTable dataTable = new DataTable();
foreach (var record in records)
{
IDictionary<string, object> dictRecord = record as IDictionary<string, object>;
if (dataTable.Columns.Count == 0)
{
foreach (var key in dictRecord.Keys)
{
dataTable.Columns.Add(key);
}
}
DataRow dataRow = dataTable.NewRow();
foreach (var key in dictRecord.Keys)
{
dataRow[key] = dictRecord[key];
}
dataTable.Rows.Add(dataRow);
}
List<Person> personList = new List<Person>();
foreach (DataRow row in dataTable.Rows)
{
Person person = new Person
{
Id = Convert.ToInt32(row["Id"]),
Name = row["Name"].ToString(),
Age = Convert.ToInt32(row["Age"])
};
personList.Add(person);
}
}
以上就是将DataTable
转换成List
的完整攻略。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:C#将DataTable转换成list的方法 - Python技术站