How to evaluate single string in IF c# - c#

is it possible to evaluate a single string in c#. The string itself will only be determined during run-time and therefore cannot be set before hand. please see example:
var a = "a == b";
if(a){
//do something
}
EDITED:
This is a actual example of what i would like computed:
var evaluationToBeDone = "MUST_CE_I = \"MUST_CE_I\"";
if(evaluationToBeDone){
// i will do something if the above is true
}

I see what you're trying to do, but the approach doesn't make sense. When you make a variable into an object, the program only reads it as letters, not any logic inside of the object. Try doing this:
var a = "MUST_CE_I"
var b = "\"MUST_CE_I\""
if (a == b)
{
do stuff
}
I assume you want your second string to have the " " quotes, so this should give you what you need. Even though the if statement will always return false since the two variables are not equal.

Related

How to write if else statement in single line in C#

In the below code, I am repeating the same code twice except one change. If there is a way to write the same in single line then it would be great.
The only changes I made is Obsc and zp based on the if..else statement.
var zp = __Services.GetValue("Z", Order.Code);
var St="";
if(sp.Label != null)
{
var Obsc = _Services.GetValue("Z", sp.Label);
St= string.Format(Obsc, .......,userProfile.DisplayName());
}
else
{
St = string.Format(zp, ......., userProfile.DisplayName());
}
Are you happy with something like this?
var code = sp.Label is null
? Order.Code
: sp.Label;
var zpOrObsc = service.GetValue("Z", code); // please use a valid variable name
var st = string.Format(zpOrObsc, ......, userProfile.DisplayName());
St = string.Format(_Services.GetValue("Z", sp.Label ?? Order.Code), ......., userProfile.DisplayName());
Make a variable to determine which parameter value you want to call GetValue with. You only need to call GetValue once and string.Format once.
var whateverTheSecondParamForGetValueIs = Order.Code;
if (sp.Label != null) {
whateverTheSecondParamForGetValueIs = sp.Label;
}
var zp = _Services.GetValue("Z", Order.Code);
var St = string.Format(zp, ......., userProfile.DisplayName());
No, this isn't a "single line", but I don't see the appeal in that. To me, this is much more readable than any ternary operator.
I'm also going to say that these variable names need quite an improvement. They don't convey any meaning.
The ternary (*) operator, also known as the "conditional operator" is basically a short-hand for "if then else " and is written like so:
result = condition ? trueValue : falseValue;
It is not comparable to an actual if ... else ... statement as it is an expression and must provide a value.
See its documentation in the C# language reference for full details: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator.
*) So called because it is the only operator that takes 3 arguments. Compare with "binary operator" and "unary operator".

C# check if variable only contains given string

I am trying to use a variable called game.PlayMode which contains a semicolon-separated list of Play Modes input by the user. The variable can literally contain anything.
An example value:
Single Player; 2-Player; 3-Player; Co-Op; Versus; Alternate
I want to check if game.PlayMode ONLY contains Single Player but I am not sure how to do that.
So far:
if (game.Playmode.Contains("Single Player"))
{
Players = "1";
}
But I know this will also return true with the example value above. How can I make sure my code returns true only if the string is an exact match?
If the variable Playmode only contains "Single Player" it is equal to that string, right?
if (game.Playmode.Trim().Replace(";", "") == "Single Player")
{
Players = "1";
}
.. and just in case if there is a semicolon, let's remove it.
In C#, you can simply use the == operator:
if (game.Playmode == "Single Player")
{
Players = "1";
}
It might be a better idea to remove any ; and any white spaces and only then do the comparison:
if (Playmode.Replace(";","").Trim()=="Single Player")
{
Players = "1";
}

String evaluation in IF condition

Lets say i have
int a = 1;
int b = 2;
string exp = "b > a";
and i want to evaluate the string expression with those variables
if(exp.SomeKindOfParseOrCast())
{
//here be magic
}
Is it possible in any simple way?
Nope, not in C# - these are parameter names, and thus are compile time values, and this expression parsing you are describing is done in runtime - the computer doesn't know the name of the parameters while it's being evaluated. Instead, you could do something a little more strict, like an expression parser - implement your own way to parse string expressions.
Very very simplified:
if(exp.Equals("b > a"))
{
if(b>a)
// do what you do if b is bigger than a
else
// do what you do with a wrong expression
}
else if (exp.Equals("a > b")
{
if(a>b)
// do what you do if a is bigger than b
else
// do what you do with a wrong expression
}
else if (exp.Equals("a = b")
{
if(a==b)
// do what you do if a is equal to b
else
// do what you do with a wrong expression
}
else
// do what you do with a badly formatted expression
if you would like to take this a step forward, you can cut spaces, make sure the expression is lowercase, etc. - there's many examples around, I personally like this one.
Is it possible in any simple way?
No, in C# this is not possible in a simple way like it were in languages such as JavaScript with its eval function. Anyway, you'd have to provide bindings of in-expression parameters to actual values.
You can use Roslyn.
Here is an example of how to compile and run your own code in runtime.
Disclaimer: I'm the owner of the project Eval Expression.NET
This library is very easy to use and allow to evaluate and compile almost all the C# language.
// For single evaluation
var value1 = Eval.Execute<bool>("b > a", new { a = 1, b = 2 });
// For many evaluation
var compiled = Eval.Compile<Func<int, int, bool>>("b > a", "a", "b");
var value2 = compiled(1, 2);

Is it possible to simplify this try-catch and if logic?

I have the following code. It's working as intended, but I just wanted to know if I can change the logic behind it to make it look simpler because I believe it's redundant.
It works like this: I fetch some data and then try to pass it through a regular expression. There are three possible outcomes:
Data is fetched ok.
Data is fetched but it doesn't contain a number. So another regex is passed.
Data is not fetched. Same regex as 2) is passed. (this is what I believe could be simplified or optimised)
At first I thought that there could be a way of checking if the regular expression returns empty or not without throwing an exception, but (correct me if I'm wrong) there isn't such a thing... so that's why I included the try/catch. Without it, if the 3rd case is met, the IF returns an exception because it says that the m2[0].Groups[1].Captures[0].Value is out of bounds, of course (because it's empty).
So... is there any way to make this look more optimised?
Thank you very much!
string regexString = #" \.\.\. .*?>(.*?)<\/a>";
MatchCollection m2 = Regex.Matches(myInput, regexString, RegexOptions.Singleline);
try
{
if (m2[0].Groups[1].Captures[0].Value.All(Char.IsDigit) == false)
{
regexString = #"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""";
m2 = Regex.Matches(myInput, regexString);
}
}
catch (ArgumentException)
{
regexString = #"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""";
m2 = Regex.Matches(myInput, regexString);
}
I'm assuming that a more accurate description of your problem is that you wish to parse a value that may or may not be there as an integer, but that your m2[0].Groups[1].Captures[0].Value.All(Char.IsDigit) throws if Value is null.
That can then be simplified to something like this:
int parsedValue = 0;
if (m2[0].Success)
{
var value = m2[0].Groups[1].Captures[0].Value;
if (!string.IsNullOrWhiteSpace(value))
{
if (int.TryParse(value, out parsedValue))
{
// do something with parsedValue, or with the fact that the value exists and is an integer
}
}
}
You could check it with IsMatch and if it doesn't match, try your second regex, if not, nothing matches
Regex normalRegex = new Regex(#" \.\.\. .*?>(.*?)<\/a>", RegexOptions.SingleLine);
Regex secondaryRegex = new Regex(#"page=.*?"">(.*?)</a>\n.*?<a class=""pagebtn""");
int valueFound;
bool numberParsed;
if (normalRegex.IsMatch(myInput)) {
// your code to check here
// use int.TryParse to parse your value and add the result to
numberParsed = int.TryParse(m2[0].Groups[1].Captures[0].Value, out valueFound);
}
if (!numberParsed) {
if (secondaryRegex.IsMatch(myInput)) {
// second code matches
} else {
// no match
}
}
In that case you don't really need your try / catch

C# if string contains more than 1 value

Good Morning,
In an if statement if we want to check if a string contains a value, we have :
if (string.Contains("Value1"))
{
}
How can we make the string compare with more values in an if statement without keep writing the whole statement? For example to avoid the below statement
if ((string.Contains("Value1") && (string.Contains("Value2")) && (string.Contains("Value3")))
{
}
Thank you
So, basically, you want to check if all of your values are contained in the string . Fortunately (with the help of LINQ), this can by translated almost literally into C#:
var values = new String[] {"Value1", "Value2", "Value3"};
if (values.All(v => myString.Contains(v))) {
...
}
Similarly, if you want to check if any value is contained in the string, you'd substitute All by Any.
Well, you could use LINQ:
string[] requiredContents = { "Foo", "Bar", "Baz" };
if (requiredContents.All(x => text.Contains(x))
{
...
}
Note that just like the short-circuiting && operator, All will stop as soon as it finds a value which doesn't satisfy the condition. (If you want to use Any in a similar way elsewhere, that will stop as soon as it finds a value which does satisfy the condition.)
I wouldn't bother for only a reasonably small number though. Without the extraneous brackets, it's really not that bad:
if (text.Contains("foo") && text.Contains("bar") && text.Contains("Baz"))
{
}
I would only start using the more general form if either there were genuinely quite a few values (I'd probably draw the line at about 5) or if the set of values was being passed in as a parameter, or varied in some other way.
As you need "your" string to contains all values:
var values = new String[] {"Value1", "Value2", "Value3"};
var s = yourString;
if (values.Count(v => s.Contains(v)) == values.Length) {
...
}
Is this the best solution? Probably not. Is it readable and extendable? Yes.
var matches = {"string1", "string2", "string3","string-n"};
var i = 0;
foreach(string s in matches)
{
if(mystring.Contains(s))
{
i++;
}
}
if(i == matches.Length)
{
//string contains all matches.
}
if(stringArray.Any(s => stringToCheck.Contains(s)))
If you want to ensure that it contains all the substrings, change Any to All:
if(stringArray.All(s => stringToCheck.Contains(s)))

Categories

Resources