how to get second record in linq to sql

2020-02-09 02:46发布

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?

9条回答
Bombasti
2楼-- · 2020-02-09 03:11

Select top 2, then select second element.

查看更多
Fickle 薄情
3楼-- · 2020-02-09 03:14
Collection.ElementAt(1)

will fetch the second record in the collection.

查看更多
冷血范
4楼-- · 2020-02-09 03:19

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.

查看更多
唯我独甜
5楼-- · 2020-02-09 03:21

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)
查看更多
兄弟一词,经得起流年.
6楼-- · 2020-02-09 03:23

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.

查看更多
甜甜的少女心
7楼-- · 2020-02-09 03:24

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();
查看更多
登录 后发表回答