score:191
Depends how much you like the linq query syntax, you can use the extension methods directly like:
var item = Items.First(i => i.Id == 123);
And if you don't want to throw an error if the list is empty, use FirstOrDefault
which returns the default value for the element type (null
for reference types):
var item = Items.FirstOrDefault(i => i.Id == 123);
if (item != null)
{
// found it
}
Single()
and SingleOrDefault()
can also be used, but if you are reading from a database or something that already guarantees uniqueness I wouldn't bother as it has to scan the list to see if there's any duplicates and throws. First()
and FirstOrDefault()
stop on the first match, so they are more efficient.
Of the First()
and Single()
family, here's where they throw:
First()
- throws if empty/not found, does not throw if duplicateFirstOrDefault()
- returns default if empty/not found, does not throw if duplicateSingle()
- throws if empty/not found, throws if duplicate existsSingleOrDefault()
- returns default if empty/not found, throws if duplicate exists
score:2
I'll tell you what worked for me:
int id = int.Parse(insertItem.OwnerTableView.DataKeyValues[insertItem.ItemIndex]["id_usuario"].ToString());
var query = user.First(x => x.id_usuario == id);
tbUsername.Text = query.username;
tbEmail.Text = query.email;
tbPassword.Text = query.password;
My id is the row I want to query, in this case I got it from a radGrid, then I used it to query, but this query returns a row, then you can assign the values you got from the query to textbox, or anything, I had to assign those to textbox.
score:4
You could use the extension method syntax:
var item = Items.Select(x => x.Id == 123).FirstOrDefault();
Other than that, I'm not sure how much more concise you can get, without maybe writing your own specialized "First" and "FirstOrDefault" extension methods.
score:9
That can better be condensed down to this.
var item = Items.First(x => x.Id == 123);
Your query is currently collecting all results (and there may be more than one) within the enumerable and then taking the first one from that set, doing more work than necessary.
Single/SingleOrDefault are worthwhile, but only if you want to iterate through the entire collection and verify that the match is unique in addition to selecting that match. First/FirstOrDefault will just take the first match and leave, regardless of how many duplicates actually exist.
score:13
These are the preferred methods:
var item = Items.SingleOrDefault(x => x.Id == 123);
Or
var item = Items.Single(x => x.Id == 123);
score:13
Just to make someone's life easier, the linq query with lambda expression
(from x in Items where x.Id == 123 select x).FirstOrDefault();
does result in an SQL query with a
select top (1)
in it.
score:19
FirstOrDefault or SingleOrDefault might be useful, depending on your scenario, and whether you want to handle there being zero or more than one matches:
FirstOrDefault: Returns the first element of a sequence, or a default value if no element is found.
SingleOrDefault: Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence
I don't know how this works in a linq 'from' query but in lambda syntax it looks like this:
var item1 = Items.FirstOrDefault(x => x.Id == 123);
var item2 = Items.SingleOrDefault(x => x.Id == 123);
Source: stackoverflow.com
Related Query
- Linq code to select one item
- In LINQ how do I select one item per ID?
- LINQ : Select one item from list but it must match two values
- How to select one item in LINQ when the other is null
- Convert string[] to int[] in one line of code using LINQ
- LINQ select one field from list of DTO objects to array
- Recursive LINQ query: select item and all children with subchildren
- linq how to select a parent with a child collection that contains one or many of an array (or list) of values
- Select one parent property and all children using linq
- Linq to select data from one table not in other table
- Default value for linq select item if query didn't return anything
- Simple Linq question: How to select more than one column?
- Linq remove only one item if there are duplicate
- LINQ select List where sub-list contains item from another list
- Select all columns but group by only one in linq
- How to Select All with a One to Many Relationship Using Linq
- C# LINQ Select objects with the same value of one property join values of other
- LINQ Source Code Available
- Linq GroupBy. Return top one item of a subset of data
- Linq select Item where it is equal to ID in another table
- How can I combine this code into one or two LINQ queries?
- Group items and select specific item from each group with LINQ
- Linq join() - Join two entities and select one
- Select value and append number to it in one LINQ statement?
- linq - how do you do a query for items in one query source that are not in another one?
- LINQ query for finding one item in list AND verifying list does not contain another item
- Select more then one node from XML using LINQ
- Using Linq select an item outside an List
- add item count to LINQ select
- LINQ group one type of item
More Query from same tag
- Unable to cast object of type 'System.Data.EnumerableRowCollection`1[System.Data.DataRow]' to same type
- How to LINQ DataTable with group by and order by to deduplicate data
- create wrapping div around top items
- How do I use a linq query to update the underlying database table
- Three-way Linq list intersection plus nulls in one list
- How to OrderBy using Linq with missing elements?
- How do I use LINQ to .Select from a List inside a Map?
- Linq to SQL - Getting the last know history entry for each divice, prior to a certain date
- Linq Expression that compare Lambda result with a constant
- LINQ query to generate XML type output on console windows and XML file
- Entity Framework Select Statement with Logic
- LINQ: How to rewrite WHERE clause to avoid: Local sequence cannot be used in LINQ to SQL
- How to set order by descending in Linq query based on aggregated column?
- How to perform Dynamic Join using LINQ
- Convert datetime to date into singleordefault method
- Linq in JSON.NET
- Join 3 tables or more
- Get all the direct Children of a specified Parent
- Selecting Particular Node List in XML
- Trying to define method similar to List<T>.ConvertAll(TOutput)
- How to use count twice on same column in a table
- Linq query that returns all records if the search item is null or empty
- How to generate a Pivot Datagridview in WinForms and EntityFramework
- orderby certain property - code improvement
- Read XML to Datatable dynamically
- LINQ filter on table to meet several criteria / DateDifference
- Get value of a class property by JsonProperty
- Querying xml child elements with prefixed namespace using LINQ to XML
- LINQ group by and getting latest value
- #Order by Not Null using expression Extension linq