C# Finding the maximum value of a string with linq

ぃ、小莉子 提交于 2019-12-29 09:10:57

问题


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();

回答1:


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




回答2:


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




回答3:


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();


来源:https://stackoverflow.com/questions/20392753/c-sharp-finding-the-maximum-value-of-a-string-with-linq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!