Having trouble converting string to int - c#

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

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
}

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.

Related

how to check the if condition with string and integer

I want to get result of a value with if condition.
i have get some value in xml file.
now what I want is
if I have a variable "a" here i have assigned some values by using dataset.
and i have another variable "b" is assigned value from xml file.
for example
int a=25;
string b=">10"
now I want to check the condition if condition with out ">" because the symbol present in b variable. I dont know how to check this condition can anybody explain me how to acheive this.
I tried like this but not working
if(a+b)
You can use the DataTable.Compute-"trick" to evaulate such expressions:
int a = 25;
string b = ">10";
bool isTrue = (bool)new DataTable().Compute($"{a}{b}", null); // true
What is supported you can read at the DataColumn.Expression remarks.
if the condition is 1!=10, how to use not equal in this code .this
condition is not working what should i do.
As the documentation tells you that is not valid syntax, you have to use <> (look at operators). So a simple approach would be either to use <> in the first place or replace them:
b = b.Replace("!=", "<>");
You can have some function to remove non numeric characters:
public int Parse(string x)
{
x = Regex.Replace(x, "[^0-9.]", "");
int result = 0;
int.TryParse(x , out result);
return result;
}
If its always a number with a symbol then:
symbol = b[0];
int bval = int.Parse(b.Substring(1))
And considering your comment for comparison you can do:
if((symbol=='>'&&a>b)||
(symbol=='='&&a==b)||
(symbol=='<'&&a<b)
){
//do your magic here
}
Of course you may need only one of < = > or you may need to have separate if conditions for each, what ever suits your needs, but I just wanted to give the idea.
I tried like this
if (b.Contains(">")) {
b = b.Replace(">", "");
if (a >Convert.ToInt32(b))
{
Console.WriteLine("value is less");
}
else
{
Console.WriteLine("value is Greater");
}
}
similarly all the symbols
First separate symbol from b:
string symbol = b[0].ToString();
string numberString = b.SubString(1);
int number = int.Parse(numberString);
Now use switch to get operation for symbol and compare:
bool result = false;
switch (symbol)
{
case ">":
if (a > number)
{
result = true;
}
break;
}
EDIT: Changed symbol declaration to avoid error: "cannot implicit convert type char to string"

Input string was not in a correct format (double)

I'm trying to convert a string (ex. "0.20055") to its equivalent double.
I already know that for some reason that string does not contain a valid double, but I don't understand why.
I really need to be able to convert this string to a double... Could anyone explain me why it's not a valid double? And how to fix this?
Here is some of my code:
double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
for(int x=0; x < numCols; x++)
{
double val;
bool r = double.TryParse(values_in_string[x],out val);
if (!r)
return;
values_in_double[x] = Convert.ToDouble(values_in_string[x]);
}
As you can see I have a string[] of lines, in which a line is like:
0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305,1.1389,0.50494
and I split them. But then I need to convert each one to a double value.
The main changes I would make to your code are to
remove the return statement since that will exit our method prematurely
use a List<double> to store your doubles (you don't have to declare a size ahead of time, which is nice because we don't know for sure how many items in the string will successfully convert to a double)
to use the val variable when adding it to the List, since double.TryParse has assigned the value to this variable already.
I also added a check to ensure that the variable numRows is not larger than the string array, because that would cause an exception in our loop:
// Mock values read from file
var input = new StringBuilder();
input.Append("0.20055,0.37951,0.39641,2.0472,32.351,0.38825,0.24976,1.3305‌​,");
input.Append("1.1389,0.50494,0.24‌​976,0.6598,0.1666,0.‌​24976,497.42,0.73378‌​,");
input.Append("2.6349,0.24976,0.14‌​942,43.37,1.2479,0.2‌​1402,0.11998,0.47706‌​,");
input.Append("‌​0.50494,0.60411,1.4‌​582,1.7615,5.9443,0.‌​11788,593.27,0.50‌​591,");
input.Append("0.12804,0.66295,0.14942,94.14,‌​3.8772,0.56393,0.214‌​02,1.741,");
input.Append("1.5‌​225,49.394,0.1853,0.‌​11085,2.042,0.051402,0.12804,114‌​.42,");
input.Append("71.05,1.0097,348690,0.12196,0.39‌​718,0.87804,0.37854,‌​0.25792,");
input.Append("2.2437,2.248‌​,0.001924‌​,8.416,5.1372,82.658‌​,4.4158,7.4277");
string[] values_in_string = inputString.ToString().Split(',');
// Declare values_in_double as a List so we don't have to worry about sizing
List<double> values_in_double = new List<double>();
// We will get errors if numCols is larger than our string array, so to be safe,
// set a variable that is the smallest of either numCols or our string array length
var numIterations = Math.Min(numCols, values_in_string.Length);
for (int x = 0; x < numIterations; x++)
{
double val;
// If TryParse succeeds, 'val' will contain the double value, so add it to our List
if (double.TryParse(values_in_string[x], NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out val))
{
values_in_double.Add(val);
}
}
There is also a much shorter way to write this code. The line basically says: For each item in values_in_string, Where double.TryParse returns true, Select val (the item as a value) And convert all the val items into a List:
string[] values_in_string = inputString.ToString().Split(',');
double val = 0;
List<double> values_in_double = values_in_string
.Where(value => double.TryParse(value, NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out val))
.Select(v => val)
.ToList();
Try this
Double.TryParse(values_in_string[x], NumberStyles.Any, CultureInfo.InvariantCulture, out val);
change
double[] values_in_double = null;
string[] values_in_string = lines[j].Split(',');
to
string[] values_in_string = lines[j].Split(',');
int arraySize = values_in_string.Length;
double[] values_in_double = new double[arraySize];
as you use
double[] values_in_double = null;
and value cannot be assign to null array
Try changing the line :
double[] values_in_double = null;
into
double[] values_in_double = new double[numCols];
Because otherwise the code you provided wouldn't run since the array is not defined (cannot be null).
The problem you have with that is the culture definition on your PC or server, if the delimitator are ',' the sistem interpret '.' as a char.
Use like this:
double vValue;
string[] vValuesString = vLines[j].Split(',');
double[] vValuesDouble = new double[vValuesString.Length];
for (int x = 0; x < vValuesString.Length; x++)
if (double.TryParse(vValuesString[x], System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out vValue))
return; 'or use' continue;'or use' vValuesDouble[x] = 0;
else vValuesDouble[x] = vValue;
NOTES:
Instance your 'double[] vValuesDouble = new double[vValuesString.Length];', you can't asing a value to a null array.
When you use a TryParce the out var return with the result of convert string to a double, you don't need to re-convert it again.
Never declare variable in a loop, it get declare and instace every run of loop.
TryParce return a bool value that indicates the result of convert you don't need declare and instance a var, just use it in a if.
Use some protocol to define your variable's name.
Try to resume your code the most posible you can.
I put the entire using System.Globalization, but you can declare the using on top or define your System.Globalization for your entire aplication.
And last, sorry for my english, is not my first languaje.
Best.

how do i check the result is between two numbers?

I have read the second line in a text file which contains 2.75 and I am trying to get it to do something if it meets certain criteria. I'm sure I have done this before and has a simple answer but I can't seen to figure it out.
string SecondLine;
using (var reader = new StreamReader(SPFile2))
{
reader.ReadLine();
SecondLine = reader.ReadLine();
}
int NewValue;
NewValue = Convert.ToInt32(SecondLine);
if ((NewValue >= 2) && (NewValue <= 2.99))
{
// Do Something
}
if ((NewValue >= 3) && (NewValue <= 3.99))
{
// Do something else
}
What have I missed out?
You are converting a decimal number to an Int32 that does not hold decimals. This will turn the number in NewValue into 2 as it truncates towards zero. You need to store the variable in a double, float or decimal whichever is best for your requirements.
See the following example that uses a double and Parse:
double newValue = Double.Parse(secondLine);
Note that if you are unsure if the value will be a double you should use Double.TryParse
double newValue;
bool result = Double.TryParse(secondLine, out newValue);
if (!result) //Parse failed
Note that if the parsing fails it may be down to your culture settings i.e. a ',' for the decimal separator not a '.'. However there is an overload for Parse and TryParse that allows you to pass culture information in.
You are trying to parse a string that represents a double into a integer
that will cause a
System.IFormatException
{"Input string was not in a correct
format."}{"Input string was not in a correct format."}
if you know it is a number with decimal part then do:
var newValue = Convert.ToDouble(secondLine);
if you know it is an integer then try:
var newValue = Convert.ToInt32(secondLine);

Convert ReadLine() to int

I have a file which contains on each line a value from {-1, 0, 1, 2, 3}. It looks like this:
I want to put all this values in an array of type int like this:
int[] linesValue = new int[NUMBER_OF_LINES];
int i;
for (i = 0; i < NUMBER_OF_LINES; i++)
{
string tmpVal = reader.ReadLine();
linesValue[i] = Convert.ToInt32(tmpVal);
}
"NUMBER_OF_LINES" is a private int and "reader" is a StreamReader.
When I run the code it gives me the error: "Input string was not in the correct format"
I tried reader.ReadLine().ToString() but it still doesn't work.
I would really appreciate if you guys can help me with this problem.
You are getting the last line or line breaks as an empty string in your string and that can't be converted into int, hence the exception. Just add a check for string.IsNullOrWhiteSpace like:
{
string tmpVal = reader.ReadLine();
if(!string.IsNullOrWhiteSpace(tmpVal))
{
linesValue[i] = Convert.ToInt32(tmpVal);
}
}
Also make sure that you are maintaining your index with this check, hence you may end up with empty entries in your array due to index increment.
You can also use File.ReadLines and parse each line to int array like:
int[] array = File.ReadLines("filePath")
.Where(r => !string.IsNullOrWhiteSpace((r)))
.Select(r => int.Parse((r)))
.ToArray();
Look for using int.TryParse method. TryParse group of methods doesn't raise an exception if parsing fails. They return a bool indicating if parsing was successful or not, and the parsed value is provided in the out parameter.

The name does not exist in the current context - grrr

In the following code, no matter what I try, the name strSide "does not exist in the current context", when I place a break point as shown. I want strSide to contain the last character in rawId and then to strip that character so that the value of rawId will convert to an integer. I don't get a compiler error, but do get a runtime error.
When the value of rawId is 8429R, the stripping works, but I cannot get the R assigned to strSide.
foreach (string fieldName in Request.QueryString)
{
rawId = fieldName;
String strSide = Convert.ToString(rawId[rawId.Length - 1]); <-- name does not exist
if (!IsNumeric(rawId)) <--break point set here.
{
rawId = StripRightChar(rawId);
}
Qty = Request.QueryString[fieldName];
int productId = 0;
if (fieldName == "txtReference")
{
strComments = Request.QueryString[fieldName];
}
Might the variable have been "optimized away"? It is not used anywhere after its creation. See this for details: How to prevent C# compiler/CLR from optimizing away unused variables in DEBUG builds?.
Do you need the value stored in strSide?
If not you could try this alternative solution
Update, since you need the value, try this:
var s = "8429L";
var numbers = s.Substring(0, s.IndexOfAny("RLB".ToCharArray()));
var letter = s.Substring(numbers.Length);

Categories

Resources