从DataTable转换为Generic List的最快方法是什么?

时间:2011-08-16 18:10:26

标签: c# generics mapping

我有一个基类,它有一个基于标识符返回DataTable的API, 我需要为每个标识符提供一个对象。

我讨厌使用数据表,所以我想写一个映射代码, 我只需要将属性映射到数据表中的特定字段。

有没有更快的方法来做而不是我的exmaple?

感谢。

public abstract class BaseClass<T> where T : BaseClass<T>
{
    protected abstract T MapObject(DataRow row);

    protected abstract int SomeIdentifier { get; }

    public IList<T> GetData()
    {
        return ConvertDataTableToGenericList(GetDataTableFromOtherSource(this.SomeIdentifier));
    }

    private IList<T> ConvertDataTableToGenericList(DataTable table)
    {
        IList<T> objectList = new List<T>();
        foreach (DataRow row in table.Rows)
        {
            objectList.Add(MapObject(row));
        }
        return objectList;
    }
}

public class DerivedClass : BaseClass<DerivedClass>
{
    public int ID { get; set; }

    protected override int SomeIdentifier
    {
        get { return 1; }
    }

    protected override DerivedClass MapObject(DataRow row)
    {
        return new DerivedClass()
        {
            ID = (int)row["ID"]
        };
    }
}

2 个答案:

答案 0 :(得分:2)

您可以更改界面以使用IEnumerable<T>yield return结果。总体性能不会提高,但您可以更快地开始处理结果。

作为样本:

private IEnumerable<T> ConvertDataTableToGenericList(DataTable table)
{
    foreach (DataRow row in table.Rows)
    {
        yield return MapObject(row);
    }
}

答案 1 :(得分:0)

这可以做你想要的,也许不是可读的?但非常简洁。我不是LINQ专家,所以也许可以清理它。另外,不知道你为什么要这样做......

//using System.Dynamic; <-- put this at the top

Linq<dynamic> list = (from r in table.AsEnumerable()
  let eo = new ExpandoObject()
  let blah = (dt.Columns.Cast<DataColumn>().All(dc => { ((IDictionary<string,object>eo).Add(dc.ColumnName, r[dc]); return true; }))
  select eo).Cast<dynamic>().ToList();

Console.WriteLine(list[0].ID); //your first ID of your DataTable.

您怎么看?

相关问题