在 C# 中将 DataTable 转换为泛型列表 [英] Convert DataTable to Generic List in C#
问题描述
免责声明:我知道在 SO 的很多地方都问过它.
我的查询有点不同.
Disclaimer: I know its asked at so many places at SO.
My query is a little different.
编码语言:C# 3.5
Coding Language: C# 3.5
我有一个名为 cardTable 的数据表,它从数据库中提取数据,我有一个 Cards 类,它只有一些属性(没有构造函数)
I have a DataTable named cardsTable that pull data from DB and I have a class Cards which have only some properties(no constructor)
public class Cards
{
public Int64 CardID { get; set; }
public string CardName { get; set; }
public Int64 ProjectID { get; set; }
public Double CardWidth { get; set; }
public Double CardHeight { get; set; }
public string Orientation { get; set; }
public string BackgroundImage { get; set; }
public string Background { get; set; }
}
我想将 cardTable 数据插入到 List 类型的对象中.
我的数据中将包含空字段,因此在我转换数据时该方法不会出错.下面的方法是最好的方法吗?
I want to insert the cardsTable data to an object of type List.
My data will be having null fields in it and so the method should not error when i convert the data. Is the below method the best way?
DataTable dt = GetDataFromDB();
List<Cards> target = dt.AsEnumerable().ToList().ConvertAll(x => new Cards { CardID = (Int64)x.ItemArray[0] });
推荐答案
你实际上可以大大缩短它.您可以将 Select()
扩展方法视为类型转换器.转换可以这样写:
You could actually shorten it down considerably. You can think of the Select()
extension method as a type converter. The conversion could then be written as this:
List<Cards> target = dt.AsEnumerable()
.Select(row => new Cards
{
// assuming column 0's type is Nullable<long>
CardID = row.Field<long?>(0).GetValueOrDefault(),
CardName = String.IsNullOrEmpty(row.Field<string>(1))
? "not found"
: row.Field<string>(1),
}).ToList();
这篇关于在 C# 中将 DataTable 转换为泛型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!