c# convert string to int in expression - c#

I'm working on a small project that transforms a list of functions into c# code.
For example: temp1.greaterThan(1); temp2.contains("a");
temp1, temp2 are expression variables in string type.
The source code is:
var temp1 = Expression.Variable(typeof(string), "temp1");
So I think I need to convert temp1 into an integer variable.
I've tried following ways but none worked:
Expression greaterThan = Expression.GreaterThan(temp1, Expression.Constant(1));
It will throw exeption because temp1 is string and hence cannot compare with 1.
Expression.GreaterThan(Expression.Call(typeof(int).GetMethod("Parse"), temp1), Expression.Constant(1));
It throws "Ambiguous match found." exception
Expression.GreaterThan(Expression.Call(typeof(Convert).GetMethod("ToInt32"), temp1), Expression.Constant(1));
Same exception: Ambiguous match found.
Expression.GreaterThan(Expression.Convert(temp1,typeof(Int32)), Expression.Constant(1));
Exception: No coercion operator is defined between types 'System.String' and 'System.Int32'.
So I'm thinking i would need to have a convert method inside the Expression.GreaterThan method.
Anyone has an idea?
Many thanks.

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));

Related

C#: Unassigned local variable with succeeded property pattern match

I have the following code using pattern matching with a property pattern that always succeeds:
var result = new { Message = "Hello!" } is { Message: string message };
Console.WriteLine(message);
The above match succeeds(result is true). However, when I try to print message, I get a:
CS0165: Use of unassigned local variable.
However, the following works:
var result = "Hello!" is { Length: int len };
Console.WriteLine(len);
Also, when I use it with an if, it just works fine:
if (new { Message = "Hello!"} is { Message: string message })
{
Console.WriteLine(message);
}
Why the discrepancies?
Why the discrepancies?
Well, it's a compile-time error, and at compile-time, it doesn't know that it would match. As far as the compiler is concerned, it's absolutely valid for result to be false, and message to be unassigned - therefore it's a compile-time error to try to use it.
In your second example, the compiler knows that it will always match because every string has a length, and in the third example you're only trying to use the pattern variable if it's matched.
The only oddity/discrepancy here is that the compiler doesn't know that new { Message = "Hello!" } will always match { Message: string message }. I can understand that, in that Message could be null for the same anonymous type... slightly more oddly, it looks like it doesn't know that it will always match { Message: var message } either (which should match any non-null reference to an instance of the anonymous type, even if Message is null).
I suspect that for your string example, the compiler is "more aware" that a string literal can't be null, therefore the pattern really, really will always match - whereas for some reason it doesn't do that for the anonymous type.
I note that if you extract the string literal to a separate variable, the compiler doesn't know it will always match:
string text = "hello";
var result = text is { Length: int length };
// Use of unassigned local variable
Console.WriteLine(length);
I suspect this is because a string literal is a constant expression, and that the compiler effectively has more confidence about what it can predict for constant expressions.
I agree that it does look a bit odd, but I'd be surprised if this actually affected much real code - because you don't tend to pattern match against string literals, and I'd say it's the string literal match that is the unexpected part here.

convert datagridview value to int

I am getting value from cell within datagridview as below and I am convert that value to int first I used the 'Convert.ToInt32' and I get error that says
Input string was not in a correct format.
I searched and found that I have to use int.tryParse
ImgId = Int32.TryParse(DGV_PatientImages.Rows[RowIndex].Cells[4].Value, out ImgId);
but I got an error saying
The best overloaded method match for 'int.TryParse(string, out int)'
has some invalid arguments
int ImgId = 0;
so I tried to user (int) Specified cast is not valid
ImgId = (int)DGV_PatientImages.Rows[RowIndex].Cells[4].Value;
and I got
Specified cast is not valid
DataGridViewRow dgvrow = DGV_PatientImages.CurrentRow;
if (dgvrow.Cells["DGV_PatientImages_ID"].Value != DBNull.Value)
{
ImgId = Convert.ToInt32(DGV_PatientImages.Rows[RowIndex].Cells[4].Value);
}
any advice please
Well DGV_PatientImages.Rows[RowIndex].Cells[4].Value is a type that can not be cast to int. It is not a string.
By the following line of code, you can simply get what its type is:
string type = DGV_PatientImages.Rows[RowIndex].Cells[4].Value.GetType().ToString();

c# Lambda with operation inside from string

I try to convert a filed with lambda definition to function.
(sourceAggr) => {
var val1 = Convert.ToDecimal(sourceAggr[0].Value);
var val2 =Convert.ToDecimal(sourceAggr[1].Value);
return val1/val2;
}, new object[2]{12,24}
I know the input (object[]) and the output and the idea is to write
fieldFromDb.convertToLambda(),new object[2]{12,24}
#RajshekarReddy the idea is write text string and convert it to function. I found a solution with Nreco module LambdaParser https://github.com/nreco/lambdaparser/

How do you check if one of two string variables exists in a string using Regex?

My code gives the following error:
operator '||' cannot be applied to operands of type 'string'
and'string'.
var searchEN = #"WEB BOOKING ID NUMBER:\s*([0-9]+)";
var searchIE = #"UIMHIR AITHEANTAIS ÁIRITHINTE GRÉASÁIN:\s*([0-9]+)";
var match = Regex.Match(item.Body.Text, searchEN || searchIE);
You can simply combine the two patterns using the | operator like:
string pattern = #"WEB BOOKING ID NUMBER:\s*([0-9]+)|UIMHIR AITHEANTAIS ÁIRITHINTE GRÉASÁIN:\s*([0-9]+)";
var match = Regex.Match(item.Body.Text, pattern);
Check out the result at this link.

cannot convert from 'System.Collections.Generic.IEnumerable<char>' to 'string'

I try to Reverse my string but I get to following error
string str = word.Reverse();
error:
cannot convert from 'System.Collections.Generic.IEnumerable' to
'string'
anyone know what should I need to do ?
You should build a new string.
string str = new string(word.Reverse().ToArray());
Calling ToArray() on an IEnumerable<T> will convert it to T[].
string has a constructor which get array of character and constructs a string.
You should join characters together to make new string.
string str = string.Join(string.Empty, word.Reverse());

Categories