Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
string 1= reportCard.1.GetText();
string 2= reportCard.2.GetText();
string 3= reportCard.3.GetText();
string 4= reportCard.4.GetText();
string 5= reportCard.5.GetText();
How do I write an if statement which check if any of the above values is false. I need to write an or operate and compare to a Y/N value
if ((1||2||3||4).Equals("No"))
This is giving error - "Cannot be applied to operands string"
I'd advise against using == to test string equality. Use String.Equals() instead.
You can also do this in one statement using Linq:
if ((new [] {string1, string2, ...}).Any(s=>string.equals(s,"No",StringComparison.CurrentCultureIgnoreCase)))
{
DoStuff();
}
This will DoStuff() if any of your strings are equal to "no" ignoring the case.
See String.Equals() and Enumerable.Any() for further reading. It should be noted that an Enumerable is any class that can be enumerated, so this includes almost all collections like arrays and lists.
Replace string1,string2,... with all of your string variable names. I'd also advise changing your report card class to have a List<string> of results (assuming all of your results are strings) rather than these fields. That way you could enumerate over it like a collection.
See List<T>.
You also can't have variable names that start with strings.
If you absolutely HAVE to use ORs, you need to perform each comparison separately and then chain them together. The way you've done it essentially reads "if string1 or string2 or string3 or string4 equals "no"". Which will evaluate as though you're saying ((string1 or string2) or (string3 or string4)) equals "no".
Obviously, "apple or pair" isn't a valid operation. So what you want is "string1 equals "no" or string2 equals "no" or string3 equals "no"...
To do this in C# you'd use something like:
if (string1 == "No" ||
string2 == "No" ||
stringN == "No" ||)
{
DoStuff();
}
I'd strongly advise against using this approach though as it's poor practice. Even if it's beyond the scope of your assignment, read up on the links I've posted and try and implement it in a more robust fashion. If this is a school assignment, most teachers will be happy to see a "better" solution than the one they're looking for. Just don't copy and paste the code I've provided and make sure you understand it.
Should rather be like below .. you need to test for the values of each variable and compound their output.
Considering you have your variable defined like below
string a = "No";
string b = "No";
string c = "No";
string d = "No";
You can check
if ((a == "No" ||b == "No" ||c == "No" ||d == "No" )
You can as well use All() method from System.Linq
if((new[] {a,b,c,d}).All(x => x == "No"))
First of all. Your code has some issues:
You cannot name variables just with numbers in C#. You could name them like, v1, v2, v3 etc.
since you want to compare boolean values why you are using string variables? Instead, you could declare your variables as follows: bool v1 = bool.Parse(reportCard.1.GetText());. Here you have to make sure that the string values which come from the object (reportCard) are suitable to boolean values. such as"True" or "False".
Then you can simply write the if statement as follows:
if (!v1 || !v2 || !v3 || !v4):
{
// do smth;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Based on msdn, C# 9 includes new "and", "or" and "not" keywords. I do not understand why, or when, one should use "or" instead of "||", "and" instead of "&&", etc.
What problem does the contextual keywords "or", "and", and "not" solve that the original conditionals ("||", "&&", etc.) didn't?
You could do:
if (a == 1 || a == 2)
or
if (a == 1 or 2)
The 2nd version is shorter and, in theory, easier to parse as a human.
It's also easier to write
if (a is (>2 and <4) or (>5 and <7) )
You're likely referring to C# 9's pattern matching. (https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements)
Using "and" and "or" is to ensure that binary operations are not ambiguous to the compiler.
This article contains more information:
https://www.infoq.com/news/2020/07/CSharp-And-Or-Not/
Borrowing Neil's example and Paurian's linked article, let's say you have this:
bool? x = SomeFunction();
if (x == null || x == true) { SomeOtherFunction(); }
x
Result
true
function called
false
function skipped
null
function called
With the introduction of pattern matching, we don't have to say x == twice. Instead we can say:
if (x is null or true) { SomeOtherFunction(); }
If we didn't have is and or as a context-sensitive keywords and used == and || instead, it would be ambiguous to the compiler, because this expression can mean something else in a pre-Patterns world.
That pre-Patterns expression is:
if (x == null || true) { SomeOtherFunction(); }
Which gives a different result for the case where x is false.
x
Result
true
function called
false
function called
null
function called
So to avoid this ambiguity, the language designers added separate keywords. See this comment on the GitHub thread for these keywords.
It's just syntactic sugar for comparing values against constant expressions. When you need to compare a variable or property to one or more constant values, you can use these Logical Patterns to shorten your code and improve readability.
This is also useful when paired with switch expressions; as per the documented example:
static string Classify(double measurement) => measurement switch
{
< -40.0 => "Too low",
>= -40.0 and < 0 => "Low",
>= 0 and < 10.0 => "Acceptable",
>= 10.0 and < 20.0 => "High",
>= 20.0 => "Too high",
double.NaN => "Unknown",
};
Here, we can execute a case based on a range of numbers aided by Logical Expressions.
Since enum values are constant, we can also use this pattern like so:
enum E {
A,
B,
C,
}
E e = E.A;
// Using logical expressions:
bool logical = e is E.A or E.B;
// V.S. the more wordy.
bool standard = e == E.A || e == E.B;
This question already has answers here:
How can I check if a string exists in another string
(10 answers)
Closed 4 years ago.
Suppose,i have two strings.NameIs and Nam.Now i can check if one string is as same as the other using :
If (string1 == string2)
But it won't work here as the strings are not the same.But a portion of it is same.What i am trying to achieve is to check if my main string has any portion of the string given...I came across String.StartWith and EndWith methods but there,i need to specify what the string might start or end with but i cannot as the strings can be anything(that's why at the beginning,i said "Suppose").
So my first question is how to achieve this ? I don't want any step=to=step instruction but atleast a little bit of direction :)
However,if i get past that,there's still a drawback and it is the Case-Sensitive issue.I've come across this but i can't seem to figure the required implementation of this in my case because i need to overcome the first issue first.
How should i achieve these ?
For ordinal comparison you can use
str1.Contains(str2);
If you need your comparison to be case-insensitive you can do
str1.IndexOf(str2, StringComparison.OrdinalIgnoreCase) >= 0;
Note that you can hide the latter in an extension method, like
static bool ContainsIgnoreCase(this string #this, string other)
=> #this.IndexOf(other, StringComparison.OrdinalIgnoreCase) >= 0;
Use String.Contains
if (stringValue.ToLower().Contains(anotherString.ToLower())) {
// Do Work //
}
Just remember to check that strings aren't null when doing contains comparing, or you will get an ArgumentNullException..
To check if substring is contained in main string, and to ignore case-sensitivity do this, its a boolean function that takes two string parameters:
public bool DoesStringExistInsideMainString(string mainString, string subString)
{
return mainString.ToLower().Contains(subString.ToLower());
}
Easiest way is this:
a = a?.ToLowerInvariant();
b = b?.ToLowerInvariant();
if(a==null || b==null || a.Contains(b) || b.Contains(a))
{
//do stuff
}
Why null propogates into true? Because if any variable is null it will definitly contains in other variable. The other two specs is just for non-null entries.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
How to find closest string(s) in list:
var list = new List<string>
{
"hello how are you",
"weather is good today",
"what is your name",
"what time is it",
"what is your favorite color",
"hello world",
"how much money you got",
"where are you",
"like you"
};
and if updated input is:
string input = "how are you";
and another one with type error:
string input = "how are ytou";
For both cases would be good to get this:
hello how are you
where are you
or even this result:
hello how are you
where are you
how much money you got
or at least just:
hello how are you
I need it to avoid minimal type error in user request to make response.
A simple approach would be to use String.Compare to get the
lexical relationship between the two comparands
Order your available items after comparing with the input and take the best match like
string bestMacht = list.OrderBy(s => string.Compare(s, input)).First();
This is only the first approach because the order of words should be ignored. Let's improve this to a full solution. After splitting the strings
string[] splittedInput = input.Split(' ');
you are able to compare the single words using a IEqualityComparer. You are free to define how many characters are possible to fail every word (in this case 2).
private class NearMatchComparer : IEqualityComparer<string>
{
public bool Equals(string x, string y)
{
return string.Compare(x, y) < 2;
}
public int GetHashCode(string obj)
{
return obj.GetHashCode();
}
}
Use this comparer and compare the words of the input and your dictionary. If two words (define it like required) are matching (whatever order) select the string.
List<string> matches = list.Where(s => s.Split(' ')
.Intersect(splittedInput, new NearMatchComparer()).Count() >= 2)
.ToList();
The result is a list of potential matches.
I would use a Levenshtein distance. This gives you a value of how different strings are. Just choose the min distance of your set.
How to calculate distance similarity measure of given 2 strings?
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How can I find equivalent(Not equal) values between strings?
//Equivalent Values
string A = "Beneficiation Return";
string B = "Return Beneficiation";
string C = "Beneficiation From Return";
string D = "Return From Beneficiation";
if i use
if(A == B)//Equal
It will only compare Equal strings and they are equivalent but not equal, is there any way to verify equivalence?
Equivalence can be: shuffled words, have or not linking words(Just
five:For,To,In,From,At.) or be shuffled and with linking words
the code would results in:
("Beneficiation Return" == "Return Beneficiation")True
("Beneficiation From Return" == "Return Beneficiation")True
("Return Beneficiation" == "Return From Beneficiation")True
I think this is what you're looking for..
string a = "Beneficiation Return";
string b = "Return Beneficiation";
string c = "Beneficiation From Return";
string d = "Return From Beneficiation";
bool isSame = !a.Except(b).Any() && !b.Except(a).Any();
The bool isSame will return true because strings a & b contain the same characters.
Compare a with c and it will return false
You could create a helper function: equivalentStrings that accepts both A and B. In that function you could do the following:
Split both strings A and B, and get two arrays of words
Check if they have same count of words (return false if not)
Check each word in arrayA if there is same word in arrayB, if yes remove the word from both arrays if not return false
If arrayA is empty (all words removed) return true.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm very new to c#. I created a forms. A richtextbox and a button in it.
I have a list of operators: Sum, Subtract,Multi,Div.I want to run a small richtextbox test. For example,in the richtextbox I write a text (eg. Sum(1,2)) and then click the button. A return result(eg.3) prints in the richtextbox.
My idea is to use string contains
foreach( var element in operatorlist)
{
string text=richtextbox.text;
if( text.contains(element)== true)
{
element(parameter1,parameter2);//something like this
}
}
I met two questions right row.
My first question is how to get the mathematical operation from the richtextbox text. Is there a better way than mine?
My second question is once we know the operator,how to allocate the two parameters in the richtextbox to the operator.
I'm not asking for coding, I'm just looking for ideas. If you have a good idea and wish to share.
You can evaluate an expression using the DataTable.Compute function:
int p1 = 1 ; string s1 = p1.ToString() ;
int p2 = 2 ; string s2 = p2.ToString() ;
int p3 = 3 ; string s3 = p3.ToString() ;
// Compute (p1+p2)*p3 ==> 9
int result = new DataTable().Compute( "("+s1+"+"+s2+")*"+s3+")","") ;
or directly:
string expression = "(1+2)*3" ;
int result = new DataTable().Compute(expression,"") ;
I think this comes down to personal style. Your way will definitely work, so good on you for that. The way I would do it is to create a Dictionary of strings to an enum. So for example, said dictionary and enum might look like this:
enum Operator { Addition = 0, Subtraction = 1, Multiplication = 2, Division = 3, etc};
var operatorDictionary = new Dictionary<string, Operator>()
{
{"Addition", Operator.Addition},
{"Subtraction", Operator.Subtraction},
etc...
};
Then to get the value you would just do
Operator operation;
operatorDictionary.TryGetValue(string operationString, out operation);
and you would have to then build some code that switches through the Operators and performs the correct operation. There is even a way of converting a string to an enum, so that would work as well.
It looks like the parameters are in a consistent format, so you would just make a simple method that splits by parenthesis and the comma, and returns the strings that it found.
Let me know if you need anything explained more.