4thSpace
4thSpace

Reputation: 44310

Getting object using LINQ Min()?

I have a LINQ query that ends with .Min(mytable.Id). This will return an integer. I then have to do another query to pull that object from that table. Is there a way to do this without writing two queries?

I could put the .Min() query as a subquery but is that any faster than two separate queries?

Upvotes: 2

Views: 3762

Answers (2)

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56162

Use OrderBy clause, then take 1st item.

Upvotes: 2

Daniel A. White
Daniel A. White

Reputation: 190905

.OrderBy(m => m.Id).FirstOrDefault();

should do it without any additional dependencies.

Since its deferred, this will be pretty quick.

Upvotes: 7

Related Questions