简体   繁体   English

从文本/数字字符串创建变量只是一个数字-Razor CSHTML

[英]Create variable just a number from text/number string - Razor CSHTML

I have a variable var1 . 我有一个变量var1 In the current context, it is pulled from the database and will be one of those values: 在当前上下文中,它是从数据库中提取的,将是以下值之一:

2, 6, 7 6t, 7q, 8q, 2,6,7 6t,7q,8q,

The number will only ever be single digit. 该数字只能是一位数字。

The number will only ever be the first characters in the variable. 该数字将永远是变量中的第一个字符。

I would like to create a single character variable (the number) from the variable I have put in. 我想从我输入的变量中创建一个字符变量(数字)。

Here for instance my variable Fac1Raw has the value of 3c and I have tried to use this code: 例如,在这里我的变量Fac1Raw的值为3c ,我尝试使用此代码:

var Fac1 = (int)(Fac1Raw.ToString().Substring(0, 1));

However I can't get it to work. 但是我无法正常工作。 Any ideas? 有任何想法吗?

You can't convert String to integer type directly. 您不能直接将String转换为整数类型。 For this, you have the Parse methods. 为此,您具有Parse方法。 If you know for sure the string won't be empty and first character is a digit, you can parse without catching errors: 如果您确定字符串不会为空并且第一个字符是数字,则可以解析而不会捕获错误:

var Fac1 = Int32.Parse(Fac1Raw.ToString().Substring(0, 1));

If you do want some validations to prevent your code from crashing: 如果您确实希望进行一些验证来防止代码崩溃:

string rawFac1 = Fac1Raw.ToString();
if (rawFac1.Length == 0 || !char.IsDigit(rawFac1[0]))
{
    //handle invalid value
}
else
{
    var Fac1 = Int32.Parse(rawFac1[0].ToString());
    //...rest of code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM