Is this possible somehow in C# : if (a==b==c==d) {...} - c#

Is there a quick way to compare equality of more than one values in C#?
something like:
if (5==6==2==2){
//do something
}
Thanks

if (a == b && b == c && c == d) {
// do something
}

In C#, an equality operator (==) evaluates to a bool so 5 == 6 evaluates to false.
The comparison 5 == 6 == 2 == 2 would translate to
(((5 == 6) == 2) == 2)
which evaluates to
((false == 2) == 2)
which would try to compare a boolwith an int. Only if you would compare boolean values this way would the syntax be valid, but probably not do what you want.
The way to do multiple comparison is what #Joachim Sauer suggested:
a == b && b == c && c == d

public static class Common {
public static bool AllAreEqual<T>(params T[] args)
{
if (args != null && args.Length > 1)
{
for (int i = 1; i < args.Length; i++)
{
if (args[i] != args[i - 1]) return false;
}
}
return true;
}
}
...
if (Common.AllAreEqual<int>(a, b, c, d, e, f, g))
This could help :)

No this is not possible, you have to split it into separate statements.
if(x == y && x == z) // now y == z
{
}
Good luck

Related

Is there a faster way to compare these decimals?

I have a stream of decimals and I am trying to compare the most recent decimal to the difference of the last 6 decimals, I may increase this number
I have the following class
public class CompareRandom
{
private const decimal DIFFERENCE = 1.8m;
public decimal a;
public decimal b;
public decimal c;
public decimal d;
public decimal e;
public decimal f;
public decimal g;
public bool Compare(decimal num)
{
this.g = this.f;
this.f = this.e;
this.e = this.d;
this.d = this.c;
this.c = this.b;
this.b = this.a;
this.a = num;
if (b != decimal.Zero && b / DIFFERENCE > a)
{
return true;
}
if (c != decimal.Zero && c / DIFFERENCE > a)
{
return true;
}
if (d != decimal.Zero && d / DIFFERENCE > a)
{
return true;
}
if (e != decimal.Zero && e / DIFFERENCE > a)
{
return true;
}
if (f != decimal.Zero && f / DIFFERENCE > a)
{
return true;
}
if (g != decimal.Zero && g / DIFFERENCE > a)
{
return true;
}
return false;
}
}
Then I initialize it as volatile
volatile static CompareRandom CompareRandom = new CompareRandom();
Then I call CompareRandom.Compare(value) synchronously as part of a loop that updates every 1ms to compare the values.
The part I am the most interested in knowing if there is a faster way to do is this part
this.g = this.f;
this.f = this.e;
this.e = this.d;
this.d = this.c;
this.c = this.b;
this.b = this.a;
this.a = num;
A successful answer will demonstrate a faster execution of the method Compare
See if you can make it faster:
https://dotnetfiddle.net/tLw8qM
https://dotnetfiddle.net/jd0bSF
You don't need to perform the division every time. Instead, multiply a by DIFFERENCE to obtain a threshold:
// Name changed to be more conventional
private const decimal Difference = 1.8m;
public bool Compare(decimal num)
{
g = f;
f = e;
e = d;
d = c;
c = b;
b = a;
a = num;
var threshold = num * Difference;
return (b != decimal.Zero && b > threshold) ||
(c != decimal.Zero && c > threshold) ||
(d != decimal.Zero && d > threshold) ||
(e != decimal.Zero && e > threshold) ||
(f != decimal.Zero && f > threshold) ||
(g != decimal.Zero && g > threshold);
};
As asides:
It's odd for a Compare method to return bool rather than an integer; given that it's not the "common" meaning of Compare, it's probably worth renaming it for clarity
It's very odd for a comparison method to change the state of an object, as this is doing (assigning to a) - another good reason to change the name.
Using a collection instead of separate variables would make all of this more maintainable, but I'd be surprised if it improved the speed.
I also really like the idea of eliminating the division, but I don't like the way you're handling booleans: the original question says something like:
if condition1 then return true;
if condition2 then return true;
if condition3 then return true;
If condition1 is true, then the code does not bother about the calculation of the other conditions (why would it, when one condition is true, then the OR of all conditions also is true).
The proposal from Jon looks as follows:
return (condition1 || condition2 || condition3)
This does exactly the same thing, but the fact if the calculation of the OR equation is determined by the compiler: if you're dealing with an older compiler, not performing optimsation, then the entire calculation is done, even if condition1 is true.

TryParse doesnt work for initial values of if statements

I am using TryParse for the code below, but when I put 1 or 2 the program doesnt continue.
int x = -1;
bool noRecords = true;
do
{
Console.WriteLine("1.Add Data");
Console.WriteLine("2.Show Data");
Console.WriteLine("0.Exit");
//x = Convert.ToInt32(Console.ReadLine());
if (x == 1)
{
Helper.ShowAddMenu(noRecords);
}
if (x == 2)
{
Helper.ShowDataMenu();
}
} //while (x != 0);
while (!int.TryParse(Console.ReadLine(), out x) || x > 2 || x < 0);
Your while loop is wrong if you want it to continue when you enter 1 or 2. The order of operations during execution of that expression in your while loop will be:
You enter the value 1
Console.Readline() will return the string "1"
int.TryParse("1", out x) will set x to 1 and will return true
!true evaluates to false
x > 2 evaluates to false because x is 1
x < 0 evaluates to false because x is 1
therefore, your while loop is while(false || false || false)
EDIT: Given the discussion in the comments below, I believe OPs use case would be best served with a code structure more like the following. Trying to cram it all into the while clause is going to be confusing.
static void Main()
{
ShowMenu();
while (true)
{
int x;
if (!int.TryParse(Console.Readline(), out x))
ShowMenu();
else if (x == 0)
break;
else if (x == 1)
Helper.ShowAddMenu(noRecords);
else if (x == 2)
Helper.ShowDataMenu();
}
}
static void ShowMenu()
{
Console.WriteLine("1.Add Data");
Console.WriteLine("2.Show Data");
Console.WriteLine("0.Exit");
}
Change !int.TryParse to just int.TryParse. TryParse returns true on success, not false.
See here dotnetfiddle.net/6JCoPQ

How to implement “stencil” pattern using linq?

I have a list of points with x,y,z coordinates and “values” say ints. I want to select a new enumerable such that for each value will be equal to ‘value + value[up] +... + value[down]’ so a stencil that uses all surrounding values only if they exist. How to do such stencil pattern with linq?
How about this, create a method to say if two values are neigbours:
public class Class1
{
public int x;
public int y;
public int z;
public int myValue;
public static bool IsNeighbour(Class1 c1, Class1 c2)
{
bool ret = ((Math.Abs(c1.x - c2.x) == 1) && c1.y == c2.y && c1.z == c2.z) ||
((Math.Abs(c1.y - c2.y) == 1) && c1.x == c2.x && c1.z == c2.z) ||
((Math.Abs(c1.z - c2.z) == 1) && c1.y == c2.y && c1.x == c2.x);
return ret;
}
}
Then, you could call:
//lc is a List<Class1>;
var result = lc.Select(currItem =>
lc.Where(anItem =>
Class1.IsNeighbour(currItem, anItem)).Sum(item => item.myValue) + currItem.myValue);
For each item it'll select its neighbours, sum them up and add the current item value.
If your logic also consider diagonal elements or other thing, all you have to do is change IsNeighbour accordingly

How to take into the account part of condition inside the condition only if some value is true

I'm trying to understand how it is possible to put condition inside condition itself.
for example, below I'm showing wrong unreal code, but clear to understand what I'm asking for without extra words:
if (a == 1 && if (b == 1) { c >= 5 })
{
/// process
}
So condition c >= 5 must be taken into the account for process only in case if b == 1 which must be exist inside one statement without using of separate function with separate conditions or as condition after condition.
Question is how take part of condition into the account inside the condition only in case if some value is true and avoid it if false and read only a == 1.
EDIT based on answer below:
int a = 1;
int b = 0;
int c = 6;
if (a == 1 && (b != 0 || c >= 5))
{
Console.WriteLine("yes");
if (c > 5)
{
Console.WriteLine("taken into the account");
}
}
else
{
Console.WriteLine("no");
}
in both cases int b = 1; and int b = 0; result is:
yes
taken into the account
desired result:
in case of int b = 1; :
yes
taken into the account
and in case of int b = 0;:
yes
if (a == 1 && (b != 1 || c >= 5 ))
Here, c >= 5 will only be evaluated when b==1.
In c# && is a short circuiting operation so b==1 will not be evaluated if a==1 does not evaluate to true.

How to make the text case insensitive?

Kindly suggest me a way to make the text case insensitive. The textbox input need to be compared irrespective of whatever case the user use
Example:
if (textBox1.Text == "Name")
{
label1.Content = "This is" + textBox1.Text;
}
If the textBox1 input is Name/ NAME/ name, the label should display the corresponding value.
I think you are looking for StringComparer.CurrentCultureIgnoreCase
if(string.Equals(textBox1.Text, "Name", StringComparer.CurrentCultureIgnoreCase))
You may also try to look at
System.Collections.CaseInsensitiveComparer
When comparing strings you really want to use the .Equals method
textBox1.Text.Equals("Name", StringComparison.CurrentCultureIgnoreCase);
The second parameter allows you to specify a StringComparison. In this example it tells it to ignore the case.
Can you please try the following:
if(textBox1.text.Equals("value",StringComparison.InvariantCultureIgnoreCase))
Hope this helps
Try This:
if(textBox1.Text.Equals("Name",StringComparision.InvariantCultureIgnoreCase))
{
label1.Content = "This is" + textBox1.Text;
}
simply you can use ToUpper or ToUpperInvariant
if (textBox1.Text.ToUpper() == "NAME")
if you need to uppercase using the casing rules of the invariant culture
if (textBox1.Text.ToUpperInvariant() == "NAME")
Try something like this
if (textBox1.Text.ToLowerInvariant() == "Name".ToLowerInvariant())
label1.Content = "This is" + textBox1.Text;
You can instantiate a comparer and reuse it throughout your code.
This Insensitive class provides a thorough set of insensitive comparison methods:
public static class Insensitive
{
private static IComparer m_Comparer = CaseInsensitiveComparer.Default;
public static IComparer Comparer
{
get{ return m_Comparer; }
}
public static int Compare( string a, string b )
{
return m_Comparer.Compare( a, b );
}
public static bool Equals( string a, string b )
{
if ( a == null && b == null )
return true;
else if ( a == null || b == null || a.Length != b.Length )
return false;
return ( m_Comparer.Compare( a, b ) == 0 );
}
public static bool StartsWith( string a, string b )
{
if ( a == null || b == null || a.Length < b.Length )
return false;
return ( m_Comparer.Compare( a.Substring( 0, b.Length ), b ) == 0 );
}
public static bool EndsWith( string a, string b )
{
if ( a == null || b == null || a.Length < b.Length )
return false;
return ( m_Comparer.Compare( a.Substring( a.Length - b.Length ), b ) == 0 );
}
public static bool Contains( string a, string b )
{
if ( a == null || b == null || a.Length < b.Length )
return false;
a = a.ToLower();
b = b.ToLower();
return ( a.IndexOf( b ) >= 0 );
}
}
Source: https://github.com/runuo/runuo/blob/master/Server/Insensitive.cs

Categories

Resources