Compare multiple values in one condition [duplicate] - c#

This question already has answers here:
Equality comparison between multiple variables
(14 answers)
Closed 7 years ago.
Int32 int1, int2, int3 = 123;
Given the above variables, how can I test that all of my variables have the value 123 without creating a collection to perform some Any or something on?
What I've Tried
if(int1 == int2 == int3 == 123)
{
// Fantastic code here
}
EDIT
I must apologise, I haven't been clear enough in my question. I'm fully aware of the && operator, I was asking with regard to 'elegance', i.e. how can I avoid repeating the value I want to compare against.
In the same way I have assigned all 3 integer variables the same value in one hit, I'd like to now make the comparison. It's looking as though there is no way of doing this, so far. I think I'm asking the impossible, I'll have to stick to the basic syntax and keep it simple.

You can create an usefull extension function:
public static bool EqualsAll<T>(this T val, params T[] values)
{
return values.All(v => v.Equals(val));
}
call it like:
bool res = 123.EqualsAll(int1,int2,int3);

You could try something like this, using the logical and operator:
if(int1 == 123 &&
int2 == 123 &&
int3 == 123)
{
}

if(int1 == 123 && int2 == 123 && int3 == 123) { // Code }
What your trying to achieve isn't possible the way you do it.
You have to separate it with &.

if(int1 == something && int2 == something && int3 == 123)
{
// Fantastic code here
}
This is how you should do it using && operator. You can check multiple conditions using this.
UPDATE :
As far as checking multiple values at one go is concerned, you can try making an array out those values and just fire a simple LINQ statement like this to check all of them for a particular value :
if (new[] { int1, int2, int3 }.All(x => x == 1))
Dont know if this fits into your requirement, just a suggestion though.

Related

c# 9 contextual keywords or,and,not [closed]

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;

How to compare two List<string[]> in C# [duplicate]

This question already has answers here:
Quickest way to compare two generic lists for differences
(18 answers)
Closed 3 years ago.
Automation - selenium using C#
We are reading a table which returns value in List<string[]>. We need to compare the values before and after an action performed, which should not affect the table content.
Is there a way to compare both
List<string[]> ExpRequestItemsWithSection
with
List<string[]> ActRequestItemsWithSection
Till now i was using below code and it works fine. But is there any other way to compare both the collections? Any idea of making this quicker and less resource intensive as i need to process a lot of lists?
bool isRequestsMatch = true;
for (int i = 0; i < ActRequestItemsWithSection.Count; i++)
{
if (!((ActRequestItemsWithSection[i][0] == ExpRequestItemsWithSection[i][0]) &&
(ActRequestItemsWithSection[i][1] == ExpRequestItemsWithSection[i][1])))
isRequestsMatch = false;
}
PFB screenshot from Immediate window
Well, if order matters, i.e.
{["A", "B"]} != {["B, A"]} // A and B swapped within the array
and
{ {
["A", "B"], ["C"], // [A, B] and [C] arrays are swapped
["C"] != ["A, "B"]
} }
Then you can check equality with a help of Linq:
bool equals = (ExpRequestItemsWithSection.Count == ActRequestItemsWithSection.Count) &&
ExpRequestItemsWithSection
.Zip(ActRequestItemsWithSection, (left, right) => left.SequenceEqual(right))
.All(item => item);
There is a System.Collections.StructuralComparisons.StructuralEqualityComparer, but for some obscure reason it is written in an ugly nongeneric way that makes it hard to use as a generic IEqualityComparer<>.
If you wrap it like this:
class GenericStructuralEqualityComparer<T> : EqualityComparer<T>
where T : System.Collections.IStructuralEquatable
{
public override bool Equals(T x, T y)
=> System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals(x, y);
public override int GetHashCode(T obj)
=> System.Collections.StructuralComparisons.StructuralEqualityComparer.GetHashCode(obj);
}
then you can do SequenceEqauls on the outer (List<>) level:
if (!
ExpRequestItemsWithSection.SequenceEqual(ActRequestItemsWithSection,
new GenericStructuralEqualityComparer<string[]>())
)
Maybe prettier than the .Zip solution?
Addition: If you like .Zip, you can use StructuralEqualityComparer without a wrapping class:
if (
ExpRequestItemsWithSection.Count != ActRequestItemsWithSection.Count
||
ExpRequestItemsWithSection.Zip(ActRequestItemsWithSection,
System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals)
.Contains(false)
)
This uses the method group System.Collections.StructuralComparisons.StructuralEqualityComparer.Equals whose signature and return type is good enough for a Func<string[], string[], bool> which .Zip takes (tried with C# 7.3 compiler).
Maybe you are looking for this answer
if (a1.SequenceEqual(a2))

Match characters of two strings [duplicate]

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.

is there any specific reason why you wouldn't use nested if statements? [closed]

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 8 years ago.
Improve this question
Is there a difference between using nested if statements and using one long if statement where there are a lot of arguments?
e.g.
if ( var1 == var2 && var3 == var4 )
{
//do something
}
or
if ( var1 == var2 )
{
if ( var3 == var4 )
{
//do something
}
}
I would like to know if there is any difference in doing things this way?
thanks
In general, the compiler will generate the same or nearly the same code for these two variants. For interpreted languages that support short-circuiting (not evaluating second part of an || or && when the outcome has been determined), it will also be pretty much the same thing.
My advice would be to use the form that represents what you want to do most clearly.
For example, if we want to check if two coordinates match:
if (x1 == x2 && y1 == y2)
Buf if your code is something like this:
if (country_of_origin == "Sweden")
{
if (today == thursday)
{
...
}
}
may make more sense...
The second style allows for checking that needs to be done independently of the first if condition.
For example, if you needed to do something in an extra condition where (var3 != var4) BUT (var1 == var2) still, it would be impossible to do with:
"if(var1 == var2 && var3 == var4)"
Thus, you would need something like:
if(var1 == var2){
if(var3 == var4){
}
//more code...
//... var3 & var 4 change...
//
if(var3 != var4){
}
}
As the commenter #Solace said, it simply allows for more flexibility.
They both do the same thing , but personally I think nested is neater and it also allows code to be executed on either side of the nested if, which is usually required
if ( var1 == var2 )
{
//do something here based on the first if but before second if
if ( var3 == var4 )
{
//do something
}
//do something here also which may be different based on the nested if result
}
But if you dont need this , then your first code is probably a tiny bit faster with just a single if
Different situations require different solutions:
if ( width == height && width == depth )
{
// Its a cube!
}
if ( x == y )
{
if ( p == q )
{
//do something for when x == y but p == q
} else {
//do something for when x == y but p != q
}
You cannot generalise for what constructs are should or should not be used - they are all appropriate in some situation.
Well, it depends what is your condition. If it's same as yours, than there is absolutely no need to choose the second way.
It's about writing clean and readable code - doing this like if (condition1 && condition2) you are suggesting that both conditions are absolutely necessary to the following fragment of code.

How to check if two string are of the same length?

I want to check if two string are of the same length. I tried the following, but it doesn't work.
string passnew = "1233";
string passcnfrm = "1234";
if((passnew.Length&&passcnfrm.Length)>6 ||(passnew.Length&&passcnfrm.Length)<15)
{
// ...
}
Why does it not work? What do I need to change?
if(passnew.Length == passcnfrm.Length &&
passnew.Length > 6 && passnew.Length < 15)
{
// do stuff
}
You are missing some basic syntax lessons. What you write inside of these brackets are conditions. We have unary operators (operating on one thing), binary operators (two) and one tertiary operator (forget about that one).
You cannot construct something like your "boundary test" with those easily.
A possible way:
(passnew.Length > 6) && (passcnfrm.Length > 6)
But you aren't testing if the length is equal anyway, even if you could use a syntax like that. You seem to want to compare if both are longer than 6 chars and shorter than 15 chars. One at 7 and one at 14 would satisfy both conditions..
if(passnew.Length == passcnfrm.Length &&
(passnew.Length < 15 && passnew.Length > 6))
{
// ...
}
Checks both are same length, and either one is more than 6 and less than 15 characters long.
that would be:
if(passcnfrm.Length.Equals(passnew.Length))
{
//do stuff
}
A probably better way to do it is:
if (( passnew != null && passcnfrm != null )
( passnew == passcnfrm )
&& ( passnew.Length > 6 && passnew.Length < 15 ))
{
// do stuff
}
Hides the length check inside the equality check which you'll probably need, it isn't in your question but the variable names make it pretty clear you're doing a password change function there. I added the null check to make sure the length checks don't throw a NullReferenceException, not needed in the example because you assign both manually, but might save some trouble if you're going to convert this to a method later on.
You can use like this:
if (s.Contains(s1[i]))
or:
boolean equalsIgnoreCase(String anotherString);
or use this method:
public static int occurrence(string [] a, string a2)
{
int occ = 0;
for (int i = 0; i < a.Length;i++ )
{
if(a[i].Equals(a2))
{
occ++;
}
}
return occ;
}

Categories

Resources