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
- Ordering a collection in mvc which is part of a DTO or viewModel
- KeyValuePair with repeated Keys
- An explicit conversion during while passing arguments
- Using LINQ to pull collection until aggregate condition met
- How to return distinct elements from my C# collection?
- in C#, how do I order items in a list where the "largest" values are in the middle of the list
- SQL query to Lambda Expression C#
- Group by on multiple columns and trace values which are not distinct
- LINQ expression that contains references to queries that are associated with different contexts
- LINQ performance - deferred v/s immediate execution
- Xamarin System.Data.Linq inside PCL
- Using .net functions to filter Entity Framework information
- LINQ UpdateCheck on parent "LastUpdatedOn" field while updating children
- If you union Two queries, do we need to run ToList() on each of them first?
- Trying to join two tables linq to Sql
- C# - How to get the Schema of a DataTable into a CSV string?
- How to order items based on a column in child table in EF
- convert sql to linq with two tables
- Mongodb c# driver: view MQL bson query generated from linq
- Linq compiled queries without passing the context
- Array to Binary Expression
- Linq Distinct across multiple tables?
- How to get max value of a string column of numbers in Entity Framework
- Concatening objects with LINQ, under a condition
- linq select C# to vb.net
- LINQ error invalid initializer member declarator
- C# word boundary regex instead of .Contains() needed
- How to use union between two different object in linq
- How to do this query using expression in LINQ?
- Can't find solution for Linq to SQL Select first letter and distinct statement