LINQ - varchar column max value - Asked By Shan on 02-May-11 07:40 AM

Hi,

 I already posted this question and I received the answers.Thanks for the replies.

 I have a varchar column in a table. I want to fetch max val of this column so I convert this to int,if the table is empty how to convert.Pls help.

var RepWidgetVal = (from o in context.ReportWidgets

select Convert.ToInt32(o.WidgetID)).Max();

TSN ... replied to Shan on 02-May-11 07:42 AM
Hi..
you need not convert it works fine to get max value...

var RepWidgetVal = (from o in context.ReportWidgets

select (o.WidgetID)).Max();

Reena Jain replied to Shan on 02-May-11 07:44 AM
hi,

here are two good links on this

http://msdn.microsoft.com/en-us/library/bb386972.aspx
http://www.thereforesystems.com/select-max-value-with-linq-to-sql/

Hope this will help you
Jitendra Faye replied to Shan on 02-May-11 07:51 AM
Dont use Max() funtion when you are getting data, because if table is null then you will get error.

so change your code like this-

var RepWidgetVal = from o in context.ReportWidgets

select Convert.ToInt32(o.WidgetID);

int maxval=0;
if(RepWidgetVal.Count()>0)
 {
    maxval=RepWidgetVal .Max();
  }

Use this code and let me know,

Shan replied to Jitendra Faye on 03-May-11 04:47 AM
Thanks it worked