user2802752
user2802752

Reputation:

C# Finding the maximum value of a string with linq

This is what I have and it keeps returning null.

It doesn't recognize the Convert.toInt32 when I add a where statement

var maxTopID = (from max in dbcontext.Topics.Local
               select max.TopicID).Max();

Upvotes: 2

Views: 13525

Answers (3)

Edper
Edper

Reputation: 9322

How about converting the TopicID in SELECT and use String.IsNullOrEmpty() to remove empty string, like:

 var maxTopID = (from max in dbcontext.Topics.Local
                 where !String.IsNullOrEmpty(max.TopicID)
                 select Convert.ToInt32(max.TopicID)).Max();

See the Demo

Upvotes: 5

SpiderCode
SpiderCode

Reputation: 10122

Check for the null condition as mentioned in below query

var maxTopID = (from max in dbcontext.Topics.Local
                 where  max.TopicId != null
                 select max.TopicID).Max();

Upvotes: 1

Nitin Varpe
Nitin Varpe

Reputation: 10694

I think you are saying that TopicID is string and you want to convert it to int

var list= (from max in dbcontext.Topics.Local
                     where  max.TopicId != null
                     select max.TopicID).ToList();

int max=0;

if (list.Count() !=0)
max=list.Select(int.Parse).ToList().Max();

max will contain max value from list which is converted to list of integer

Upvotes: 1

Related Questions