Reputation: 10981
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?
Upvotes: 19
Views: 23450
Reputation: 1955
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.
Upvotes: 1
Reputation: 10572
Collection.ElementAt(1)
will fetch the second record in the collection.
Upvotes: 2
Reputation: 742
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();
Upvotes: 9
Reputation: 51
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.
Upvotes: 5
Reputation: 9119
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()
Upvotes: 9
Reputation: 46465
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)
Upvotes: 3