2012-04-23 88 views
2

我想比较两个字符串值,就像这样:比较两个字符串值

if (lblCapacity.Text <= lblSizeFile.Text) 

我该怎么办呢?

+3

文本属性是数值吗?你可以使用'Int32.Parse' – Siege 2012-04-23 12:58:18

+2

在这种情况下,<<=是什么意思? – Oded 2012-04-23 12:58:48

+1

@Oded:我认为是相对于字典排序不大或相等 – DonCallisto 2012-04-23 13:00:10

回答

0

使用Int32.Parse,Int32.TryParse或其他等价物。然后您可以数字比较这些值。

0

看起来像标签包含数字。那么你可以尝试Int32.Parse

if (int.Parse(lblCapacity.Text) <= int.Parse(lblSizeFile.Text)) 

当然,你可能要添加一些错误检查(看Int32.TryParse也许解析INT值存储在一些变量,但这是基本的概念

2

如果。你有一个整数的文本框,然后,

int capacity; 
int fileSize; 

if(Int32.TryParse(lblCapacity.Text,out capacity) && 
    Int32.TryParse(lblSizeFile.Text,out fileSize)) 
{ 
    if(capacity<=fileSize) 
    { 
     //do something 
    } 
} 
4
int capacity; 
int fileSize; 

if (!int.TryParse(lblCapacity.Text, out capacity) //handle parsing problem; 
if (!int.TryParse(lblSizeFile.Text, out fileSize) //handle parsing problem; 

if (capacity <= fileSize) //... do something. 
+0

+1,如果有人为我的商店编写代码,这将是我需要的 – Steve 2012-04-23 13:04:45

0

比较是你所需要的。

int c = string.Compare(a , b); 
+3

当您希望'“11”<“2”== true'时。 – 2012-04-23 13:11:42

+0

这个问题并未指出它的数值 – Yeshvanthni 2012-04-23 13:35:08

17

我假设您正在比较lexicographical order中的字符串,在这种情况下,您可以使用Static方法String.Compare。

例如,您有两个字符串str1和str2,并且您想查看str1是否在字母表中的str2之前出现。您的代码如下所示:

string str1 = "A string"; 
string str2 = "Some other string"; 
if(String.Compare(str1,str2) < 0) 
{ 
    // str1 is less than str2 
    Console.WriteLine("Yes"); 
} 
else if(String.Compare(str1,str2) == 0) 
{ 
    // str1 equals str2 
    Console.WriteLine("Equals"); 
} 
else 
{ 
    // str11 is greater than str2, and String.Compare returned a value greater than 0 
    Console.WriteLine("No"); 
} 

上面的代码会返回yes。有许多重载版本的String.Compare,包括一些可以忽略大小写的地方,或者使用格式化字符串。退房String.Compare

+0

当然我忘了提及Control.Text属性返回一个字符串,这就是为什么我使用String.Compare的原因。 – 2012-04-23 13:27:25