tags:

views:

185

answers:

2

I have a table with a list of names. This table has an ID column that is an autoincremented number. I would like to display on my website something like,

"6,523,213 names created so far."

So, I need to get the highest currently index/ID number from my names table.

I can think of a few ways to do it, I could OrderBy ID by desc and select the first one. But this might not be the fastest way to do this. I could also stick a field some place and increment it every time I insert a new name into the database.

Is there any easier/fast LINQ express to do this?

A: 

I think what you really want to do is count the rows - not get the highest index. Consider what happens when a record is deleted - the number of registered names decreases by one, but the highest index does not...

In plain SQL, you could use this:

 SELECT COUNT(ColumnName) FROM TableName

If you really want to do it with LINQ, I think this will work.

Tomas Lycken
+3  A: 

You could simply use either the COUNT or MAX methods of LINQ:

Assumming a DataContext of that name and an entity named "Names" with a primary key called "Id". Either of these would work:

DataContext db = new DataContext();
var nameCount = db.Names.Count();

var nameCount = db.Names.Select(n => n.Id).Max();
Jose Basilio
Jose - you do not need the Select, you can simply call Max with a selector eg var nameCount = db.Names.Max(n => n.Id);
Winston Smith