C# LINQ 选择第一
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10149982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ Select First
提问by bumble_bee_tuna
Hi I have this bit of linq code
嗨,我有一点 linq 代码
var fp = lnq.attaches.First(a => a.sysid == sysid).name;
When profiled it generates the following t-sql
分析后,它会生成以下 t-sql
SELECT TOP (1) [t0].[sysid], [t0].[name], [t0].[att_size], [t0].[cid], [t0].[flags], [t0].[contents]
FROM [lntmuser].[attach] AS [t0]
The way I look at it, it is returning like a select *, which will cause the query to perform a table scan rather then use an index. Bad for performance.
在我看来,它像 select * 一样返回,这将导致查询执行表扫描而不是使用索引。对性能不利。
How could I select just the name column, like:
我怎么能只选择名称列,例如:
SELECT TOP (1)[t0].[name] FROM [lntmuser].[attach] AS [t0]
Thanks in advance
提前致谢
Edit: Broken Glasses Solution profiles as desired
根据需要编辑:Broken Glasses Solution 配置文件
SELECT TOP (1) [t0].[name]
FROM [lntmuser].[attach] AS [t0]
WHERE [t0].[sysid] = @p0
采纳答案by BrokenGlass
Project to the nameproperty before using First():
name使用前投影到属性First():
var fp = lnq.attaches.Where(a => a.sysid == sysid)
.Select(a => a.name)
.First();
This doesn't change the use of an index though - for that your Whereclause is responsible (in your initial query the lambda you passed to First()). Both queries benefit from an index on the namecolumn, the second one is just faster because only one column value has to be materialized.
这不会改变索引的使用 - 因为你的Where子句负责(在你的初始查询中你传递给的 lambda First())。两个查询都受益于name列上的索引,第二个查询更快,因为只需要实现一个列值。

