简体   繁体   English

Linq与DataTable .ToList()非常慢

[英]Linq with DataTable .ToList() very slow

facts.UnderlyingDataTable is a DataTable facts.UnderlyingDataTable是一个数据表


var queryResults4 = //get all facts
    (from f in facts.UnderlyingDataTable.AsEnumerable()
        where f.RowState != DataRowState.Deleted &&
            FactIDsToSelect.Contains(f.Field<int>("FactID"))
        select f);

var queryResults5 = (from f in queryResults4.AsEnumerable()
    orderby UF.Rnd.Next()
    select f);


return queryResults5.ToList();

The problem is this line queryResults5.ToList(); 问题是这一行queryResults5.ToList();

It returns a list of DataRows. 它返回DataRows的列表。 But is super slow to do this. 但是这样做太慢了。

I am happy to return any object that implements IEnumerable . 我很高兴返回实现IEnumerable任何对象。 What should I do? 我该怎么办? I seems the conversion from whatever the var is to List<DataRow> is slow. 我似乎从var到List<DataRow>都很慢。

Thanks for your time. 谢谢你的时间。

First, not the ToList itself is slow but the query that gets executed in this method. 首先,不是ToList本身很慢,而是使用此方法执行的查询。 So maybe your DataTable contains many rows. 因此,也许您的DataTable包含许多行。 I assume also that FactIDsToSelect is large which makes the Contains check for every row slow . 我还假设FactIDsToSelect很大,这会使每行的Contains检查变慢。

You could use CopyToDataTable to create a new DataTable with the same schema instead of a List since that is more natural for an IEnumerable<DataRow> . 您可以使用CopyToDataTable创建具有相同架构而不是List的新DataTable ,因为这对于IEnumerable<DataRow>更自然。 However, as i have mentioned, that would not solve your performance issue. 但是,正如我已经提到的那样,这不能解决您的性能问题。

You could optimize the query with a Join which is much more efficient: 您可以使用更有效的Join优化查询:

var q =   from row in UnderlyingDataTable.AsEnumerable()
          where row.RowState != DataRowState.Deleted 
          join id in FactIDsToSelect
          on row.Field<int>("FactID") equals id
          select row;
var newTable = q.CopyToDataTable();

Why is LINQ JOIN so much faster than linking with WHERE? 为什么LINQ JOIN比链接到WHERE这么快?

Please try with following. 请尝试以下。

List<DataRow> list = new List<DataRow>(UnderlyingDataTable.Select("FactID = " + id.ToString(),DataViewRowState.Unchanged));

You may need to change the DataViewRowState argument in .Select method. 您可能需要在.Select方法中更改DataViewRowState参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM