(one line if) ? bool is true - give me string [duplicate] - c#

This question already has answers here:
Ternary with boolean condition in c#
(7 answers)
Closed 5 years ago.
I can't wrap by head around this even though I've read many stackoverflow threads.
I check if the page has a specific property value like so:
bool categoryCount = CurrentPage.HasValue("blogCategories");
I want to transform this into a one-line if statement so I can parse a string to a class like illustrated below:
string situation = (categoryCount.ToString() == "true") ? '' : '';
PS: I apologize for the missing logic behind my thoughts/goal. I'm new at programming.

What about:
string situation = (CurrentPage.HasValue("blogCategories"))
? "Has the value" : "Has NOT that value";
You should change two things:
do not work with ToString() == "True", simply put the boolean (expression) in the condition part of the ternary operator: it is inefficient to call ToString() and furthermore if the specifications change, it might stop working (actually true.ToString() returns "True", with a capital, so it will not work with your code);
use string literals "some string", not char literals 'a': the result is supposed to be a string, not a char.
By comparing with "true", this will not work:
csharp> true.ToString()
"True"
csharp> true.ToString() == "true"
false
But even if it would work, it would be rather unsafe: if later the designers of the .NET library change their minds, then your program could stop working correctly. Usually I think it is better not to rely on the format of a ToString() method. These tend to be culture specific, and furthermore usually do not offer hard constraints with respect to the output format anyway.

You don't need to convert to string to use ternary. You can simply just do this:
string situation = categoryCount ? "Executes if true" : "Executes if false";
The ternary condition doesn't need to be a string, just the returns.

You don't need to convert a bool to a string to find out if it's true.
Do you know what this returns if categoryCount has the boolean value true?
bool x = categoryCount.ToString() == "true";
It returns the boolean value true. If categoryCount is true, then it is true that its string representation is equal to "true". But categoryCount is true already.
It is exactly the same as this:
bool x = categoryCount;
Also, a string in C# uses double quotes, not single quotes.
So:
string situation = categoryCount ? "one string" : "another string";

Related

Evaluating an arbitrary string expression in c#

I have a method that needs to return true or false based upon a string expression that is passed in to it. The string expression could look like:
("ASDF"=="A" || "BED"!="BED") && (5>=2)
or any valid C# expression that evaluates to a Boolean result. I only need to support basic string and math comparison operators plus parentheses. I have tried NCalc but when I pass it this:
"GEN"=="GEN" || "GEN"=="GENINTER"
it generates the error
System.ArgumentException: Parameter was not defined (Parameter 'GEN')
at NCalc.Domain.EvaluationVisitor.Visit(Identifier parameter)
when I use the following code:
NCalc.Expression e = new(filterExpression, EvaluateOptions.IgnoreCase);
var filterResultObject =e.Evaluate();
Any thoughts appreciated on how to evaluate an arbitrary expression since I will not know the expression until run time.
Greg
I have found that NCalc will properly evaluate the strings but only if they are single quoted such as !('GEN'=='GEN'). If the strings are double quoted, the error is thrown.
For your example you can use NFun package like this:
string str = "\"ASDF\"==\"A\" || \"BED\"!=\"BED\") && (5>=2)"
bool result = Funny.Calc<bool>(str)

How to check if string contains special part [duplicate]

This question already has answers here:
How can I check if a string contains a character in C#?
(8 answers)
Closed 5 years ago.
How I can check if my string has the value ".all" in. Example:
string myString = "Hello.all";
I need to check if myString has .all in order to call other method for this string, any ideas how I can do it?
you could use myString.Contains(".all")
More info here
Use IndexOf()
var s = "Hello.all";
var a = s.IndexOf(".all", StringComparison.OrdinalIgnoreCase);
If a = -1 then no occurrences found
If a = some number other than -1 you get the index (place in the string where it starts).
So a = 5 in this case
Simply call .Contains(".all") on the string object:
if (myString.Contains(".all")
{
// your code to call the other method goes here
}
There is no need for regex to do that.
Optionally, as mentioned by #ZarX in comments, you can check if the string ends with your keyword with .EndsWith(".all"), which will return true if the string ends with your keyword.

Verify empty field Selenium C#

I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
Console.WriteLine("This field can not be empty");
}
Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?
Thank you in advance!
If it's string, then you can use string.Empty or "", because " " contains a space, therefore it's not empty.
For those 20 digits, you can use a bit of a workaround field.ToString().Length == 20 or you can repetitively divide it by 10 until the resulting value is 0, but I'd say the workaround might be easier to use.
This is more of a general C# answer. I'm not exactly sure how well it's gonna work in Selenium, but I've checked and string.Empty and ToString() appear to exist there.
For Empty / White space / Null, use following APIs of the string class
string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)
For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits
string pattern = #"^\d{20}$";
var booleanResult = Regex.Match(value,pattern).Success
I'm not sure that this way will work in your case. Code:
var firstName = driver.FindElement(By.Id("name_3_firstname"));
will return to You IWebElement object. First you should try to get text of this element. Try something like firstName.Text or firstName.getAttribute("value");. When u will have this you will able to check
:
var text = firstName.getAttribute("value");
if(string.IsNullOrEmpty(text)){ // do something }
if(text.length == 20) {// do something}

How do I format an Enum? [duplicate]

This question already has answers here:
Enum ToString with user friendly strings
(25 answers)
Closed 7 years ago.
I need my enum to return a formatted string to the view, for example:
public enum status
{
NotStarted,
InProgress,
}
return: Not Started and In Progress. How I do it? Thanks (language C#)
enums don't do that. You'd need to provide a map of enum values to display strings or you could do something like define an attribute with a display string that you can use (which requires some fiddly reflection to get the attribute for a given enum value, but has the advantage that you can define the display name right where you define the enum value).
For example, you can use a Dictionary<status,string> to map them:
var myMap = new Dictionary<status,string>()
{
{ status.NotStarted, "Not Started" },
{ status.InProgress, "In Progress" }
};
Now to get the display string for a given status value s you'd just do something like:
var s = status.NotStarted;
var displayString = myMap[s]; // "Not Started"
Of course, you'd put this in a class somewhere so it's only defined once in one place.
Another rather brittle, quick-and-dirty way to do it would be to exploit the fact that your enum names are Pascal-cased and use something like a regex to take the enum name and insert an extra space. But that's pretty hacky. So you could do something like:
var r = new Regex("([A-Z][a-z]*)([A-Z][a-z]*)");
var displayString = r.Replace(s.ToString(),"$1 $2"); // "Not Started"
But that would choke on any enum values that didn't fit the pattern of two Pascal-cased words. Of course, you could make your regex more flexible, but that's beyond the scope of the question.
Calling ToString on an emum value is the equivalent to Enum.GetName which would give you the named value i.e.
Console.WriteLine(status.NotStarted.ToString()) // NotStarted
From there, assuming the format is consistent, you could convert the string from Pascal casing to a whitespace separated string e.g.
string result = Regex.Replace(status.NotStarted, "([a-z])([A-Z])", "$1 $2");
Console.WriteLine(result); // Not Started
See example.
Enum.GetName(typeof (Status), Status.InProgress));

Difference between converting integer to string "" +1 and 1.ToString()

What is the difference when I convert integer to string like this way:
string str = "" + 1;
And
string str =1.ToString();
The first method is equivalent to string str = "" + 1.ToString(); and uses 2 intermediate strings before producing the result. That amounts to 3 strings total: an empty string, "1", and the result of the concatenation, which is also "1".
The second method doesn't use any intermediate string. It's also more readable and clearly expresses your intent (which is to convert the integer into a string).
With ToString() you assign a return value of the method. By using "" + 1 the ToString() method is called by the CLR.
See Automatic .ToString()?
int.ToString() is the tool for converting an integer into a string.
However, the C# allows you not to call this method when concatenating strings via plus operator, and the framework calls .ToString() instead of you.

Categories

Resources