英文:
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<int> ShipmentQtys = _MyContext
.MaxShipmentEntries
.Where(m => m.PartNo == currentPart)
.Select(m => 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 <yourtype>[i];
ShipmentQtys.Select((x,i) => 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 <yourtype>[i];
ShipmentQtys.Select((x,i) => 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论