Converting string expression to Integer Value using C#
Use NCalc : stable, simple, and powerful
c# convert string to int in expression
You should use int.Parse
to parse a string instead of explicit conversion. Note that int.Parse
has a few overloads, that's why you get an "Ambiguous match found" exception.
var temp1 = Expression.Variable(typeof(string), "temp1");
//use int.Parse(string) here
var parseMethod = typeof(int).GetMethod("Parse", new[] { typeof(string) });
var gt = Expression.GreaterThan(Expression.Call(parseMethod, temp1), Expression.Constant(1));
How can I convert String to Int?
Try this:
int x = Int32.Parse(TextBoxD1.Text);
or better yet:
int x = 0;
Int32.TryParse(TextBoxD1.Text, out x);
Also, since Int32.TryParse
returns a bool
you can use its return value to make decisions about the results of the parsing attempt:
int x = 0;
if (Int32.TryParse(TextBoxD1.Text, out x))
{
// you know that the parsing attempt
// was successful
}
If you are curious, the difference between Parse
and TryParse
is best summed up like this:
The TryParse method is like the Parse
method, except the TryParse method
does not throw an exception if the
conversion fails. It eliminates the
need to use exception handling to test
for a FormatException in the event
that s is invalid and cannot be
successfully parsed. - MSDN
Convert string to INT in C# (When String is 'E0305' To convert INT is not Work
If you just want to skip invalid string value, it is better to use TryParse
instead of returning 0 (which might be valid value). At your calling code it should look like this:
string val = "F0005";
if (int.TryParse(val, out int i) {
// parse success. you can use i here
}
else {
// parse failed.
}
If you really want it to be 0, this should work
string val = "F0005";
int i = int.TryParse(val, out int x) ? x : 0;
Set string as int constant using Expression class
I think for a wide variety of types, a simple Convert.ChangeType
will do the trick:
XElement expression = GetMyCurrentMember();
//<member type="System.Int32">5</member>
var formatProv = CultureInfo.InvariantCulture;
var type = Type.GetType(expression.Attribute("type").Value, false, true);
var value = Convert.ChangeType(expression.Value, type, formatProv);
return Expression.Constant(value, type);
Please note that by providing a format provider you can explicitly specify the culture you want to use in the conversion.
How to convent string math formula to int at run time in c#
@Rand Random, @Charlieface
First of all, if you come across a question in a language you don't know, I recommend you to skip it. Do not create invalid claims!
int.parse(); is used to
convert a string integer to an integer value.
But clearly in this case this line =>
int value = int.parse(code); // value should be 2
case's an error,
(because code is not an integer)
And to do what I was asking u don't need a compiler. I actually did it without it!!
using static System.Math;
using Project = System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
class YesICanWithoutACompiler
{
static void Main(string[] args)
{
string code = "1+ 1 + 1*1 * (((((((3!=63))?(2==4?5:1):7))==8)?2:(4==6?7:3) ))";
string formula = getFormular(code); // outputs: 1+ 1 + 1*1 * (3)
Console.WriteLine("yes I can!: " + new System.Data.DataTable().Compute(formula, ""));
Console.ReadLine();
}
static int IndexOfAny(string source, string[] items, int startat = 0)
{
List<int> indexes = new List<int>();
for (int f = 0; f < items.Length; f++)
{
int loo = source.IndexOf(items[f], startat);
if (loo != -1)
{
indexes.Add(loo);
}
}
if (indexes.Count > 0)
{
return indexes.Min();
}
else
{
return -1;
}
}
static bool conditoin(int x, string mark, int y)
{
switch (mark)
{
case "!=":
return (x != y);
case "==": return (x == y);
case ">=": return (x >= y);
case "<=": return (x <= y);
default: return false;
}
}
static string getFormular(string code)
{
int ind = IndexOfAny(code, new string[] { "==", ">=", "<=", "!=" });
while (ind != -1)
{
int condition1 = int.Parse(string.Join("", code.Substring(0, ind).Reverse().SkipWhile(c => !char.IsDigit(c)).TakeWhile(d => char.IsDigit(d))));
string conditioin = code.Substring(ind, 2);
int condition2 = int.Parse(string.Join("", code.Substring(ind + 2).TakeWhile(d => char.IsDigit(d))));
string arvo = "";
if (conditoin(condition1, conditioin, condition2))
{
arvo = code.Substring(1 + code.IndexOf("?", ind + 2)).Trim();
if (arvo.StartsWith("("))
{
int ndent = 1;
int h = 0;
while (h < arvo.Length && ndent != 0)
{
h++;
if (arvo[h] == ')') ndent--;
if (arvo[h] == '(') ndent++;
}
arvo = arvo.Substring(0, h + 1);
}
else
{
arvo = string.Join("", arvo.TakeWhile(s => s != ':'));
}
}
else
{
arvo = code.Substring(1 + code.IndexOf(":", ind + 2)).Trim();
if (arvo.StartsWith("("))
{
int ndent = 1;
int h = 0;
while (h < arvo.Length && ndent != 0)
{
h++;
if (arvo[h] == ')') ndent--;
if (arvo[h] == '(') ndent++;
}
arvo = arvo.Substring(0, h + 1);
}
else
{
arvo = string.Join("", arvo.TakeWhile(s => s != ')'));
}
}
int f = code.IndexOf("?", ind);
int indent = 0;
while (f > 0 && indent != -1)
{
f--;
if (code[f] == ')') indent++;
if (code[f] == '(') indent--;
}
int t = f;
indent = 1;
while (t < code.Length && indent != 0)
{
t++;
if (code[t] == ')') indent--;
if (code[t] == '(') indent++;
}
code = code.Remove(f, (t - f) + 1).Insert(f, arvo);
ind = IndexOfAny(code, new string[] { "==", ">=", "<=", "!=" });
}
return code;
}
}
Convert string to integer
Use this:
int yourInteger;
string newItem;
newItem = textBox1.Text.Trim();
Int32 num = 0;
if ( Int32.TryParse(textBox1.Text, out num))
{
listBox1.Items.Add(newItem);
}
else
{
customValidator.IsValid = false;
customValidator.Text = "You have not specified a correct number";
}
This assumes you have a customValidator.
Convert string[] to int[] in one line of code using LINQ
Given an array you can use the Array.ConvertAll
method:
int[] myInts = Array.ConvertAll(arr, s => int.Parse(s));
Thanks to Marc Gravell for pointing out that the lambda can be omitted, yielding a shorter version shown below:
int[] myInts = Array.ConvertAll(arr, int.Parse);
A LINQ solution is similar, except you would need the extra ToArray
call to get an array:
int[] myInts = arr.Select(int.Parse).ToArray();
Converting string to number in c#
It is working fine. 0x00000178
is the hexadecimal representation of 376
.
Your Hex button is enabled in Visual Studio.
Related Topics
Convert Datatable to Generic List
I am Getting Failed to Load Resource: Net::Err_Blocked_By_Client with Google Chrome
What Does Default(Object); Do in C#
What Is the Efficiency and Performance of Linq and Lambda Expression in .Net
How to Handle Add to List Event
Does Mstest Have an Equivalent to Nunit's Testcase
How to Reference Microsoft.Office.Interop.Excel Dll
How to Increase Executiontimeout for a Long-Running Query
Executenonquery for Select SQL Statement Returning No Rows
Fake-Scrolling Containers with Very Many Controls
Converting String Expression to Integer Value Using C#
Practical Applications of Bitwise Operations
Using Lambda Expressions for Event Handlers
ASP.NET Core Model Binding Error Messages Localization