Home > DeveloperSection > Forums > How to find max value of a column in a datatable?
Mark Devid
Mark Devid

Total Post:102

Points:714
Posted on    January-27-2014 2:56 AM

 C# C# 
Ratings:


 1 Reply(s)
 1121  View(s)
Rate this:

I am trying to find the max value of a column in a datatable.

 Below is my code:-

var maxVal = dsloadReferralCodes.Tables["dtReferralCodesTable"].AsEnumerable().Max(r =>  Convert.ToBoolean(int.TryParse(r.Field<string>("ROWNUM"), out intROWNUM)) ? (int?)intROWNUM : null);

and below id the error i am getting while trying to get the max value and assigning it to intROWNUM

Unable to cast object of type 'System.Decimal' to type 'System.String'

Can someone help me in resolving the issue. This has been troubling me since long.

Thanks in advance...



Pravesh Singh

Total Post:411

Points:2881
Posted on    January-27-2014 3:16 AM

Hi Mark,

You can get it in simple manner with DataTable.Select() :

DataRow [] dr = dsloadReferralCodes.Tables["dtReferralCodesTable"].Select("ROWNUM= MAX(ROWNUM)"); 

 if(dr !=null)

    {

     // Console.WriteLine(dr[0]["RowNum"]);

        int maxVal=Convert.ToInt32(dr[0]["RowNum"]);

    }


Don't want to miss updates? Please click the below button!

Follow MindStick