Click here to Skip to main content
15,890,527 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am storing some values in a temporary datatable which created with asp.net code.(not using sql) .Sample values as follows,

ID FILENAME PATH
--------------------------
1 txt1 C:\NewFolder
2 txt2 C:\NewFolder
3 txt3 C:\NewFolder
I want to get the last value of ID column. (ie. 3)

Please help.

Regards
Jithesh
Posted

1 solution

I assume you're talking about a System.Data.DataTable ..?

If the last row always has the highest ID then simply get the last row of the table:
C#
DataRow lastRow = yourDataTable.AsEnumerable().Last();

int id = lastRow.Field<int>("ID"); // maybe you have to change "int" to the actual column type here
string fileName = lastRow.Field<string>("FILENAME");
string path = lastRow.Field<string>("PATH");


If the last row is not neccessarily the one with the highest ID and you have not defined the ID-column as primary key, then:
C#
int highestID = yourDataTable.AsEnumberable()
                             .Select(row => row.Field<int>("ID"))
                             .Max(); // above comment about "int" applies here too

DataRow rowWithHighestID = yourDataTable.AsEnumberable()
                             .Single(row => row.Field<int>("ID") == highestID);


If you do have defined the ID-column as primary key, then:
C#
int highestID = yourDataTable.AsEnumberable()
                             .Select(row => row.Field<int>("ID"))
                             .Max(); // above comment about "int" applies here too

DataRow rowWithHighestID = yourDataTable.Rows.Find(highestID);


Edit:

The above "middle" solution would be sub-optimal in case your DataTable can contain a lot of rows because it iterates twice over the row collection. This would be better, albeit a bit "uglier":
C#
int highestID = -1;
int indexOfHighestID = -1;
for (int i=0; i<yourDataTable.Rows.Count; i++)
{
    int id = row.Field<int>("ID");
    if (id > highestID)
    {
        highestID = id;
        indexOfHighestID = i; 
    }
}
if (indexOfHighestID > 0)
{
    DataRow rowWithHighestID = yourDataTable.Rows[indexOfHighestID];
    // do something with that row here
}


Another Edit:

If you need to do that regularly in your application, the best way would be to define a primary key on the ID-column and somewhere keep the highest/last ID you inserted around so that you don't have to find out which one it was. Then it would be simply this:
C#
DataRow rowWithHighestID = yourDataTable.Rows.Find(highestID);
 
Share this answer
 
v4
Comments
jithesh a 14-Mar-15 11:49am    
Thanks Alot......;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900