This is how i return Datatable
Then how to assign that datatable to list<> (is it possible to assign datatable to list<>) ??
public DataTable Vehiclelist(string Vehicle)
{
SqlCommand newCmd = conn.CreateCommand();
newCmd.Connection = conn;
newCmd.CommandType = CommandType.Text;
newCmd.CommandText = "SELECT * from where Vehicle_No ='" + Vehicle+ "'";
SqlDataAdapter da = new SqlDataAdapter(newCmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
return dt;
}
以上代码段从表中读取数据并作为Datatable返回 然后告诉如何将此数据表分配给List&lt;&gt;在Code背后或者告诉如何将数据读取为List&lt;&gt;来自数据库
答案 0 :(得分:2)
与DataTable相反,List<T>
是强类型泛型集合。因此,您可以从定义代表此集合的每个元素的模型开始:
public class Vehicle
{
public int Number { get; set; }
public string Make { get; set; }
public string Model { get; set; }
...
}
然后:
public List<Vehicle> Vehiclelist(string Vehicle)
{
var result = new List<Vehicle>();
using (SqlConnection conn = new SqlConnection("PUT YOUR CONNECTION STRING HERE"))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "SELECT * FROM Vehicles WHERE Vehicle_No = @Vehicle_No";
cmd.Parameters.AddWithValue("@Vehicle_No", Vehicle);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
result.Add(new Vehicle
{
Number = reader.GetInt32(reader.GetOrdinal("Vehicle_No")),
Make = reader.GetString(reader.GetOrdinal("Vehicle_Make")),
Model = reader.GetString(reader.GetOrdinal("Vehicle_Model"))
});
}
}
return result;
}
}
还要注意参数化查询的使用,以避免代码容易受到的SQL注入。
为了简化将数据库列映射到CLR类型的过程,您可以考虑使用ORM,例如Dapper
或ADO.NET Entity Framework。
答案 1 :(得分:0)
你的意思是这样的:
var results = dt.AsEnumerable()
.Select(row => new {VehicleNo = row["Vehicle_No"].ToString()})
.ToList();
这将为您提供一个列表(它将是匿名类型),但是如果您有一个可以映射到的具体类型,您也可以实例化它:
List<Vehicle> results = dt.AsEnumerable()
.Select(row => new Vehicle {VehicleNo = row["Vehicle_No"].ToString()})
.ToList();
答案 2 :(得分:0)
List list = dt.AsEnumerable()。ToList();