Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Getting Nth value with Linq

How can I get the Nth row using Linq? both columns are text so I cant use min/max

Upvotes: 38

Views: 18828

Answers (5)

Abhijeet
Abhijeet

Reputation: 1

you can use order by with skip

var nthItem = items.OrderByDescending(<your order by>).skip(n-1).FirstOrDefault();

Upvotes: 0

Paul Chernoch
Paul Chernoch

Reputation: 5553

An alternative (.Net 3.5 and later) is to use ElementAtOrDefault.

var nthItem = items.ElementAtOrDefault(n-1);

The method's index is zero-based, so if you want the third element, you pass 2 for the index.

Upvotes: 32

Anthony Faull
Anthony Faull

Reputation: 17957

var nthItem = items.Skip(n-1).FirstOrDefault();

Upvotes: 4

cjk
cjk

Reputation: 46425

You can use skip and take.

var result = myData.OrderBy(<your order by>).Skip(5).Take(1);

Upvotes: 6

Mark Seemann
Mark Seemann

Reputation: 233150

var nthItem = items.Skip(n).First();

Upvotes: 54

Related Questions