Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the second element in a collection, using LINQ? [duplicate]

Tags:

c#

linq

I have a silly question. I have a database and I need to get second item not only the first one. Im opening the first one easy way

var source = _context.SourceLogs.Where(a => a.SourceID == user.ID).First()

but I dont know how to open the second one. Im new to C# so only thing I was thinking about was this

var source = _context.SourceLogs.Where(a => a.SourceID == user.ID).First(-1)

But that obviously does not work. Any kind of help is appreciated. Thanks.

like image 555
shad0wec Avatar asked Aug 28 '15 11:08

shad0wec


4 Answers

You can use LINQ's Skip method to jump over the first and take the one after:

var source = _context.SourceLogs.Where(...).Skip(1).First();

What Skip does is create a new IEnumerable containing all items except the first. Then, you take the First() of that new IEnumerable.

like image 112
Avner Shahar-Kashtan Avatar answered Nov 14 '22 01:11

Avner Shahar-Kashtan


var source = _context.SourceLogs.Where(a => a.SourceID == user.ID).ElementAt(1);
like image 41
Kędrzu Avatar answered Nov 14 '22 00:11

Kędrzu


Try this:

var source = _context.SourceLogs.Where(a => a.SourceID == user.ID).OrderBy(a => a.SourceID).Skip(1);

Update: If you want to get just second item in the list, you can add .First() at the end of the query:

var source = _context.SourceLogs.Where(a => a.SourceID == user.ID).OrderBy(a => a.SourceID).Skip(1).First();
like image 2
Sirwan Afifi Avatar answered Nov 14 '22 00:11

Sirwan Afifi


You can just skip the first one and take first from it.

var source = _context.SourceLogs.Where(a => a.SourceID == user.ID).Skip(1).First()
like image 1
Bhushan Firake Avatar answered Nov 14 '22 01:11

Bhushan Firake