how to get second record in linq to sql
-
05-07-2019 - |
Question
I have an exchange rate table. I need to get current rate and previous rate and then compare results.
I can get first record using FirstOrDefault
.
When I am using ElementAtOrDefault
, this error shows "The query operator 'ElementAtOrDefault' is not supported". How can I get the second record?
Solution
You can try this:
var query=data.Skip(1).Take(1);
OTHER TIPS
Take() returns null if the element is not there (so is equivalent to FirstOrDefault()).
If you'd rather an exception was thrown (cos the second element is not there) like First() then use:
Skip(1).Single()
There's a detail not explicitly mentioned here: FirstOrDefault
returns an Element
, Skip(1).Take(1)
returns a set of 1 element; i.e. the type returned by Skip(1).Take(1)
is IEnumerable
, while FirstOrDefault
is not.
If you use
.Take(2)
you will get the first and second.
EDIT- If you need both the first and second, then the above will be more efficient than runing your query twice:
.Take(1)
.Skip(1).Take(1)
Try this simple implementation this might be useful
var query= (from p in db.Person where p.Person == person_id select p);
var firstResult = query.First();
var secondResult = query.Skip(1).Take(1).Single();
var thirdResult = query.Skip(2).Take(1).Single();
Select top 2, then select second element.
Collection.ElementAt(1)
will fetch the second record in the collection.
Use .Skip(1) method
As John Anderson already pointed out Skip(1).Take(1)
returns an IEnumerable
of size 1.
In order to get the 2nd entry itself or else a null
(i.e. no exceptions), I'm using the following:
var secondEntry = collection?.Skip(1)?.FirstOrDefault();
It may not work in your specific case, but may be useful for use cases of other.