运营商'>'不能应用于'object'和'string'类型的操作数 [英] Operator '>' cannot be applied to operands of type 'object' and 'string'

查看:88
本文介绍了运营商'>'不能应用于'object'和'string'类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

private void button1_Click(object sender, EventArgs e) 
       {           
        string s=null;
        foreach (DataRow a in amDataSet.students.Rows)
        {
            if (a["id"] > s)
            {
                s = a["id"].ToString();
            }
        }
        MessageBox.Show(s);
        }





我的尝试:



我想在massbox的[id]字段中显示MAX值



What I have tried:

I want to display the MAX value in the ["id"] field in massbox

推荐答案

字符串实际上没有max值 - 他们通过依次查看每个字符进行比较,整个比较基于第一对不同的字符。因此,作为字符串的数值的排序顺序总是看起来很奇怪:1,10,11,... 19,2,20,21 ......并且您的ID字段不太可能是字符串,大多数是INT或而是基于GUID。



如果你想在整数列中找到最大ID值,那么根本不要使用字符串:

Strings don't really have "max" values - they compare by looking at each character in turn and the whole comparison is based on the first pair of different characters. As a result, the sort order for numeric values as strings always looks wierd: 1, 10, 11, ... 19, 2, 20, 21 ... And your ID field is unlikely to be string anyway, most are INT or GUID based instead.

If you are trying to find the max ID value in an integer column, then don't use strings at all:
int max = int.MinValue;
foreach (DataRow a in amDataSet.students.Rows)
   {
   int val = (int) a["ID"];
   max = val > max ? val : max;
   }
MessageBox.,Show(val.ToString());

如果是包含数值的字符串列,则使用适当的Parse方法:int.Parse,double .Parse等,并比较该数据类型。

If it is a string column containing numeric values, then use the appropriate Parse method: int.Parse, double.Parse, etc., and compare that datatype instead.


这篇关于运营商'>'不能应用于'object'和'string'类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆