在不将 IQueryable 转换为 List 的情况下,是否可以对其进行索引?

huangapple go评论77阅读模式
英文:

Is indexing on an IQueryable possible without converting to List?

问题

我有一个Razor Pages Web应用程序,其中我的OnGet方法包含一个LINQ查询,该查询查找不超过5条记录的集合(我的源是我创建的非常大的SQL视图):

IQueryable<int> ShipmentQtys = _MyContext
    .MaxShipmentEntries
    .Where(m => m.PartNo == currentPart)
    .Select(m => m.ShipQty);

这是速度很快的,但问题是我需要根据结果进行索引。我知道我需要使用.ToList(),但这会显著减慢我的加载时间,我猜这是因为我的视图很大,所以我不知道如何解决这个问题。

我需要对它进行索引,以便在我的应用程序中定义的5个字段中显示每条记录(最多5条)。有一篇帖子建议使用.ElementAt,但LINQ不支持这个方法。

ShipQtyField1 = ShipmentQtys[0];
ShipQtyField2 = ShipmentQtys[1];
//等等。

是否有其他方法可以对IQueryable(或IEnumerable)进行索引,或者在我的情况下是否有不索引的替代方法?

英文:

I have a Razor Pages web application where my onget method has a LINQ query that finds a collection of no more than 5 records (my source is very large SQL view I've created):

IQueryable&lt;int&gt; ShipmentQtys = _MyContext
    .MaxShipmentEntries
    .Where(m =&gt; m.PartNo == currentPart)
    .Select(m =&gt; m.ShipQty);

It's speedy, but the problem is that I need to index off of the results. I know that I need to use .ToList() instead, but this significantly slows down my load time by a long shot, I'm assuming because my view is huge, so I'm stuck on how to get around the problem.

I need to index it in order to display each record (up to 5) in 5 fields that I have defined in my application. One post suggested using .ElementAt, but that is not supported in LINQ.

ShipQtyField1 = ShipmentQtys[0];
ShipQtyField2 = ShipmentQtys[1];
//etc.

Is there another way I can index an IQueryable(or an IEnumerable), or an alternative to indexing at all in my circumstance?

答案1

得分: 1

你可以通过使用选择重载来访问索引:

var tmp = new &lt;yourtype&gt;[i];
ShipmentQtys.Select((x,i) =&gt; tmp[i] = x);

这与ToArray相同,仅供演示;

或者你可以枚举IEnumerable:

var e = ShipmentQtys.GetEnumerator();
if (e.MoveNext())
   ShipQtyField1 = e.Current;
if (e.MoveNext())
   ShipQtyField2 = e.Current;

对于你的专用变量,我建议使用后一种版本。

但是没有随机访问的方式,它始终是连续访问。

英文:

You can access the index, by using the select overload

  var tmp = new &lt;yourtype&gt;[i];
  ShipmentQtys.Select((x,i) =&gt; tmp[i] = x);

That's the same as ToArray, it's just for demonstration;

Or you can enumerate the IEnumerable

  var e = ShipmentQtys.GetEnumerator();
  if (e.MoveNext())
     ShipQtyField1 = e.Current;
  if (e.MoveNext())
     ShipQtyField2 = e.Current;

For your dedicated variables, I would recommend the latter version.

But there is no way for a random access, it's always continuous access only.

huangapple
  • 本文由 发表于 2020年1月4日 00:48:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582282.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定