【问题标题】:LINQ query for an in-memory List takes seconds on ToList() call对内存中列表的 LINQ 查询在 ToList() 调用上需要几秒钟
【发布时间】:2018-08-16 04:47:11
【问题描述】:

即使对于内存中的列表,以下 LINQ 查询也很慢。执行需要几秒钟。

我尝试了 List 和 IQueryable 两者都很慢。

你能提供任何建议为什么它很慢吗?

编辑:

该列表有 350,000 行。逻辑从存储过程转换为列表中的缓存表,并从内存中检索数据,而不是多次访问数据库。

var list = GetData().AsQueryable(); //GetData returns List<MDEntity>
var query = (from g in list join ux in list on new {
    Page = sPage, g.Property, Product = sProdAll, Section = (Guid?) null
  }
  equals new {
    ux.Page, ux.Property, ux.Product, Section = (Guid?) null
  }
  into ux_join from ux in ux_join.DefaultIfEmpty() join up in list on new {
    Page = sPage,
      g.Property,
      Section = (Guid?) null
  }
  equals new {
    up.Page,
      up.Property,
      Section = (Guid?) null
  }
  into up_join from up in up_join.DefaultIfEmpty() where(up.Product ?? string.Empty) == sProd || up.Product == sProdAlt where g.Section == (Guid?) null &&
  g.Page == sPage &&
  ((g.Product ?? string.Empty) == sProd || g.Product == sProdAlt || g.Product == sProdAll) orderby g.Property,
  g.Product,
  g.Language select new MDEntity {
    Property = g.Property,
      Product = (up.Page ?? string.Empty) == string.Empty ? Coalesce(up.Product, ux.Product, null, null) : Coalesce(up.Product, "SA", null, null),
      Language = Coalesce(up.Language, ux.Language, null, null),
      Value = Coalesce(up.Value, ux.Value, null, null)
  });
var result = query.ToList();

【问题讨论】:

  • 您的列表中有多少个元素?
  • 要么使用 ToList() 将其真正放入内存中,要么在存储过程中执行,以便更好地控制查询
  • 如果您最终将大型集合连接在一起,L2O 可能会很慢。如果这是您的问题,您可以使用此技术加快速度:github.com/mcintyre321/LinqToAnything/wiki/…
  • 该查询的具体目标是什么?很难说,但该列表上有 2 个自我加入,可能是不必要的。我看到使用了很多有问题的构造,但如果我们无法弄清楚它在做什么,就很难给出一个潜在的解决方案。
  • @mcintyre321 因为列表很大,我会尝试索引选项。谢谢。

标签: c# linq


【解决方案1】:

ToList() 调用是实际查询的执行点。因此,您上面的那一大段代码在您调用 ToList() 的那一刻被延迟执行。

鉴于我看到您能够使用 AsQueryable,我几乎可以肯定这最终是一个隐藏的数据库查询。虽然,我可能是错的。

在 ToList() 调用之前,C# 不执行 SQL 调用。所以实际上,它不是内存中的操作。

这是一个相当复杂的查询,所以我并不感到惊讶,数据库可能需要几秒钟才能完成查询,然后 C# 才能返回结果列表。

【讨论】:

  • 他/她说“GetData 返回列表
  • @mcintyre321 如果这是真的,为什么还要select new MDEntity
猜你喜欢
  • 2013-05-24
  • 1970-01-01
  • 1970-01-01
  • 2014-01-01
  • 2014-07-10
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-02-18
相关资源
最近更新 更多