Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ Select First

Tags:

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 
like image 846
bumble_bee_tuna Avatar asked Apr 14 '12 00:04

bumble_bee_tuna


People also ask

How do I get my first record in LINQ?

Solution 1int id = 2; var item = lstData. FirstOrDefault(k => k.ID == id); if (item != null) { // use the Item object to read the properties. // your code here... } if we are in doubt that duplicate records may contains, then we can go for FirstOrDefault .

What is LINQ select?

LINQ Select comes under the Projection Operator, the select operator used to select the properties to display/selection. Select operator is mainly used to retrieve all properties or only a few properties which we need to display. It is used to select one or more items from the list of items or from the collection.

What is first method LINQ?

LINQ First() Method In LINQ, the First() method/operator returns the first element from the sequence of items in the list/collection or the first element in the sequence of items in the list based on the specified condition.

Which function is used to get first record in LINQ collection?

Accepted Answer. data . GroupBy( x => x.


1 Answers

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.

like image 136
BrokenGlass Avatar answered Sep 21 '22 06:09

BrokenGlass