ebattulga
ebattulga

Reputation: 10981

how to get second record in linq to sql

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

Answers (9)

Teodor Tite
Teodor Tite

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

Nalan Madheswaran
Nalan Madheswaran

Reputation: 10572

Collection.ElementAt(1)

will fetch the second record in the collection.

Upvotes: 2

Clyde
Clyde

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

John Anderson
John Anderson

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

bytedev
bytedev

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

cjk
cjk

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

Sadegh
Sadegh

Reputation: 6854

Use .Skip(1) method

Upvotes: 0

Anton Gogolev
Anton Gogolev

Reputation: 115809

Select top 2, then select second element.

Upvotes: 1

Valentin V
Valentin V

Reputation: 25759

You can try this:

var query=data.Skip(1).Take(1);

Upvotes: 42

Related Questions