LINQ选择第 [英] LINQ Select First

查看:113
本文介绍了LINQ选择第的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有LINQ这段代码



  VAR FP = lnq.attaches.First(A =>一种。 SYSID SYSID ==)。名称; 

在异形它生成以下的T-SQL

  SELECT TOP(1)[T0]。[SYSID],[T0]。[名],[T0]。[att_size],[T0]。[CID],[ T0] [国旗],[T0]。[内容] 
从[lntmuser]。[附] AS [T0]

我看它的样子,它返回像一个SELECT *,这将导致查询执行表扫描而不是使用索引。 。不好的表现。



我怎么能只选择name列,如:

  SELECT TOP(1)[T0]。[名] FROM [lntmuser]。[附] AS [T0] 

在此先感谢






编辑:
碎玻璃解决方案型材根据需要

  SELECT TOP(1)[T0]。[名] 
从[lntmuser]。[附] AS [T0]
WHERE [T0]。[SYSID] = @ P0


解决方案

项目的名称属性,使用前第一()

  VAR FP = lnq.attaches.Where(A => a.sysid == SYSID)
。选择(A => a.name)
。首先();

这不会改变使用索引虽然 - 为你的其中,子句负责(在你的初始查询,你传递给拉姆达优先())。两个查询来自于名称列的索引中获益,第二个就是快,因为只有一列值已被物化。


Hi I have this bit of linq code

var fp = lnq.attaches.First(a => a.sysid == sysid).name;

When profiled it generates the following 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.

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

SELECT TOP (1) [t0].[name]
FROM [lntmuser].[attach] AS [t0]
WHERE [t0].[sysid] = @p0

解决方案

Project to the name property before using 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 Where clause is responsible (in your initial query the lambda you passed to First()). Both queries benefit from an index on the name column, the second one is just faster because only one column value has to be materialized.

这篇关于LINQ选择第的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆