how to get second record in linq to sql

2020-02-09 02:42发布

问题:

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?

回答1:

You can try this:

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


回答2:

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()


回答3:

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.



回答4:

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)


回答5:

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();


回答6:

Select top 2, then select second element.



回答7:

Collection.ElementAt(1)

will fetch the second record in the collection.



回答8:

Use .Skip(1) method



回答9:

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.