将2个String数组列表放入DataTable的快速方法?

时间:2015-01-15 09:40:46

标签: c# linq datatable

我目前正在使用2个字符串列表来创建数据表。我想知道那里是否有比在那里使用2个foreach循环更快的方法?

DataTable table = new DataTable();
table.Columns.Add("id");
table.Columns.Add("parentId");
table.Columns.Add("value");

List<MyData1> parents = new MyDataHandler.GetAllParents(); // Has id, name
List<MyData2> childs = new MyDataHandler.GetAllChilds(); // has id, parentId, name

// Fill the list with all parents
foreach (MyData1 p in parents)
{
    table.Rows.Add(new String[] {p.id, null, p.name});
}

// Fill the list with all childs
foreach (MyData2 c in childs)
{
    table.Rows.Add(new String[] {c.id, c.parentId, c.name});
}

之前提到过,我想知道是否有更快的方法可以做到这一点(因为table.Rows没有addRange方法),因为这看起来非常简单并且对我来说很慢。

请注意: MyData 2中的ParentId引用MyData1中的id。两个列表都来自数据库

public List<MyData1> GetAllParents()
{
    using (MyEntity entity = new MyEntity())
    {
        return (from e in entity.MyData1 select new MyData1 { id = e.id, name = e.name }).ToList();
    }
}

public List<MyData2> GetAllChilds()
{
    using (MyEntity entity = new MyEntity())
    {
        return (from e in entity.MyData2 select new MyData2 { id= e.id, name = e.name, parentId = e.parentId}).ToList();
    }
}

1 个答案:

答案 0 :(得分:0)

该变体不是更快但可能更简单:

var parents = new MyDataHandler.GetAllParents()
    .ToDataTableModel(p => p.Id, p => null, p => p.Name);
var childs = new MyDataHandler.GetAllChilds()
    .ToDataTableModel(c => c.Id, c => c.ParentId, c => c.Name);
var table = parents.Concat(childs).ToList().ToDataTable();

您只需要2个分机和1个新课程:

public class DataTableModel
{
    public int Id;
    public int? ParentId;
    public object Value;
}

public static class Extensions
{
    public static List<DataTableModel> ToDataTableModel<TSource>(this List<TSource> sourceList, Func<TSource, int> getId, Func<TSource, int?> getParentId, Func<TSource,object> getValue)
    {
        var tempList = new List<DataTableModel>();
        var query = from entry in sourceList
                    select new DataTableModel
                    {
                        Id = getId(entry),
                        ParentId = getParentId(entry),
                        Value = getValue(entry)
                    };
        return query.ToList();
    }

    public static DataTable ToDataTable<TSource>(this List<TSource> list)
    {
        DataTable table = new DataTable();
        foreach (var prop in typeof(TSource).GetFields())
        {
            table.Columns.Add(prop.Name, 
                Nullable.GetUnderlyingType(prop.FieldType) ?? prop.FieldType);
        }
        foreach (var entry in list)
        {
            var row = table.NewRow();
            foreach (var prop in typeof(TSource).GetFields())
            {
                row[prop.Name] = prop.GetValue(entry) ?? DBNull.Value;
            }
            table.Rows.Add(row);
        }
        return table;
    }
}

ADDED:修正了一些错误。刚完成测试。工作正常。