Having trouble converting string to int

2019-09-01 12:04发布

In my program I have a treeView. In the section that I am working with, the node's displayNames are numerical integer values, but are displayed as strings. I have come to a point in my program where I need to convert and temporarily store these displayNames in an integer variable. I usually use Regex.Match() to do this with no problem, but in this scenario I am getting the compiler error: Cannot implicitly convert type 'string' to 'int'.

This is my code:

//This is the parent node as you may be able to see below
//The children of this node have DisplayNames that are integers
var node = Data.GetAllChildren(x => x.Children).Distinct().ToList().First(x => x.identify == 'B');

//Get # of children -- if children exist
if (node.Children.Count() > 0)
{
     for (int i = 0; i < node.Children.Count(); i++)
     {
          //Error on this line!!**
          IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, @"\d+").Value;
     }
}

*NOTE: DisplayName.Value is a string

2条回答
Ridiculous、
2楼-- · 2019-09-01 12:43

The problem is becuase you're casting from Match to int in this call

IntValue = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, @"\d+").Value;

Try something like this:

Match m = Regex.Match(node.Children.ElementAt(i).DisplayName.Value, @"\d+").Value;
int value = m.Matches[0] //You'll have to verify this line, I'm going from memory here.
查看更多
欢心
3楼-- · 2019-09-01 12:44

To get from string to int, use int.Parse(string), it returns the int represented by the passed string and throws if the input format is incorrect.

int.Parse(node.Children.ElementAt(i).DisplayName.Value)

You can also use int.TryParse if you don't want the throw. in that case you would use:

int parsedValue;
if (int.TryParse(node.Children.ElementAt(i).DisplayName.Value, out parsedValue))
{
  ///Do whatever with the int
}
查看更多
登录 后发表回答