将字符串数组转换为int列表
我的代码是
my code is
string tabtype = "5,7,11";
string[] strTabTypes = tabtype.Split(',');
List<int> lstInt = new List<int>();
for (int i = 0; i < strTabTypes.Length; i++)
lstInt.Add(Convert.ToInt32(strTabTypes[i]));
将字符串转换为int时出错
如何解决
getting error when converting string to int
how to solve it
这几乎肯定是一个数据问题,因为tabtype的内容不是你所期望的。
所以试试这个:
It's almost certainly a data problem, in that the contents of tabtype are not what you expected.
So try this:
string[] strTabTypes = tabtype.Split(',');
List<int> lstInt = new List<int>();
for (int i = 0; i < strTabTypes.Length; i++)
{
try
{
lstInt.Add(Convert.ToInt32(strTabTypes[i]));
}
catch(Exception ex)
{
Console.WriteLine("Problem converting input {0} : \"{1}\" to an integer:\n{2}", i, strTabTypes[i], ex.Message);
}
}
它至少会告诉你问题是什么。
It will at least tell you what the problem is.
// using Linq; // required
string[] strTabTypes = tabtype.Split(',');
List<int> lstInt = strTabTypes.Select(str => Convert.ToInt32(str)).ToList();
请注意,此方法将用于如果'strTabTypes数组中的任何字符串对转换为Int32无效,则抛出System.FormatException错误。
这是一种可以进行错误检查的方法使用Linq进行转换:
Note that this approach is going to throw a System.FormatException error if any of the strings in the 'strTabTypes array are not valid for conversion to Int32.
Here's one way you could approach error-checking in the conversion using Linq:
Int32 testInt;
List<int> lstIn2 = strTabTypes
.Select(str => Int32.TryParse(str, out testInt) ? testInt : Int32.MaxValue)
.ToList();
在这个例子中,如果有任何字符串无法转换为Int32,则返回Int32.MaxValue:2,147,483,647:十六进制0x7FFFFFFF。
但是,也许正确的做法是将转换放在Try / Catch块中并处理错误,或者重新抛出错误?
In this example, if there is any string that can't be converted to Int32, then Int32.MaxValue is returned: 2,147,483,647 : hexadecimal 0x7FFFFFFF.
But, perhaps the right thing for you to do is put the conversion in a Try/Catch block and handle the error, or re-throw the error ?
下面的代码提供了更强大的解决方案与原始解决方案相比。
The code below provides for a more robust solution compared to your original solution.
string tabtype = "1,5,11"; // Just an example
// This way you make sure that there are no empty positions in the string array
string[] strTabTypes = tabtype.Split(new char[] { ',' },
StringSplitOptions.RemoveEmptyEntries);
List<int> lstInt = new List<int>();
foreach (string s in strTabTypes) // foreach is easier to use in this case
lstInt.Add(Convert.ToInt32(s.Trim())); // Removes head and tail spaces
您当然可以根据解决方案1添加错误检查。
You can of course add an error check according to solution 1.