简体   繁体   English

linq查询将特定数目的列追加到字符串中

[英]linq query appending specific number of column into a string

I have this linq code: 我有此linq代码:

db.Accounts.Where(o => o.name.Contains(prefixText.Trim())).Select(o => (o.name + ":" + o.account_id)).Take(5)

Now lets say the actual result is 1000 but I only took the top five result. 现在说实际结果是1000,但我只获得前五名。

My question is, will all the 1000 result (name and id) will get appended first and then take the top 5 result? 我的问题是,是否所有1000个结果(名称和ID)都将首先附加,然后取前5个结果?

If yes then how can I modify it to only append the top 5 result not the whole query results? 如果是,那么我如何修改它以仅附加前5个结果而不是整个查询结果?

I have no answer to your question but to make sure you don't concat all 1000 records, you could change you LINQ as 我没有回答您的问题,但是要确保您未合并所有1000条记录,可以将LINQ更改为

db.Accounts.Where(o => o.name.Contains(prefixText.Trim())).Take(5).
    Select(o => (o.name + ":" + o.account_id)));

When done on a database, that will, of course, be up to the database implemention, although I think it's most likely that the database engine would first choose the records it wants (ie, just the top 5), and then format them based on the select. 在数据库上完成时,这当然要取决于数据库的实现,尽管我认为数据库引擎最有可能首先选择所需的记录(即,仅前5位),然后根据其格式进行格式化在选择上。

When this is performed on an in-memory collection (eg a List<>), then you can be assured that the Select if definitely only be executed 5 times (at most). 当在内存中的集合(例如List <>)上执行此操作时,可以确信Select(如果确实)仅执行5次(最多)。

It basically works on a "pull" model: Assuming you have something like a .ToList() at the end to actually drive it, The ToList asks the Take() for the first item, and the Take asks the Select, which asks the Where which asks the collection. 它基本上可以在“拉”模型上工作:假设最后有一个.ToList()来实际驱动它,ToList向第一个项目询问Take(),而Take向选择询问,哪里问集合。 The where keeps asking the collection until it finds one that meets the condition, and then it passes that the Select which passes it to the Take which passes it to the ToList() which then asks Take for another, and the cycle starts again. where一直询问集合,直到找到一个满足条件的集合,然后它传递Select ,它将Select传递给Take ,并将Take传递给ToList() ,然后ToList()再次请求Take ,然后循环再次开始。 After Take has returned the fifth, it tells the ToList , "OK ,We're done. Stop asking for more". Take返回第五条之后,它告诉ToList :“好,我们完成了。停止要求更多”。

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

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