数据表转换为泛型列表在C# [英] Convert DataTable to Generic List in C#

查看:130
本文介绍了数据表转换为泛型列表在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  数据表到泛型列表(内存泄漏?)



  

可能重复:结果
  转换DataTable中列出<>



  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/441023/fastest-way-to-convert-datatable-to-generic-list\">Fastest方式数据表转换为泛型列表


免责声明:我知道它在在SO这么多的地方问结果
我的查询是有点不同。

编码语言:C#3.5

我有一个名为cardsTable数据表,从数据库中提取数据和我有只有一些属性类卡(无构造函数)

 公共类卡
{
    公众的Int64 CardId中获得{;组; }
    公共字符串CardName {搞定;组; }
    公众的Int64专案编号{搞定;组; }
    公共双CardWidth {搞定;组; }
    公共双CardHeight {搞定;组; }
    公共字符串方位{搞定;组; }
    公共字符串的BackgroundImage {搞定;组; }
    公共字符串背景{搞定;组; }
}

我要的cardsTable数据插入到类型列表的对象。结果
我的数据将其中具有空字段,所以当我转换数据的方法应该没有错误。是下面方法的最佳方式?

  DataTable的DT = GetDataFromDB();
清单&LT;卡&GT;目标= dt.AsEnumerable()了ToList()ConvertAll(X =&gt;新建牌{CardId中=(Int64的)x.ItemArray [0]});


解决方案

您可以真正缩短下来增色不少。你可以把选择()扩展方法作为一种类型的转换器。则转换可以写成这样:

 列表&LT;卡&GT;目标= dt.AsEnumerable()
    。选择(行=&gt;新建卡
    {
        //假设0列的类型可为空&LT;长&GT;
        CardId中= row.Field&LT;&长GT;(0).GetValueOrDefault()
        CardName = String.IsNullOrEmpty(row.Field&LT;串GT;(1))
            ? 未找到
            :row.Field&所述;串GT;(1),
    })了ToList()。

Possible Duplicate:
DataTable to Generic List (memory leak?)

Possible Duplicate:
Convert DataTable to List<>

Possible Duplicate:
Fastest way to convert datatable to generic list

Disclaimer: I know its asked at so many places at SO.
My query is a little different.

Coding Language: C# 3.5

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; }
}

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] });

解决方案

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆