Don't understand how work logical operator works - c#

how its work?? -
Debug.WriteLine("{0}, {1}, {2}",(dy == 0), (dx == 0),((dy == 0)&&(dy == 0)));
output:
true, false, true
how is this possible?

((dy == 0)&&(dy == 0))
You're checking if the same variable is equal to 0 twice, the same variable you have already established is equal to zero before.
((dy == 0)&&(dx == 0)) will return false since one expression evaluates to true and the other to false so joining them with && which is an AND boolean operator will result in false.

If (dy == 0) = true,
(dy == 0)&&(dy == 0) will also be true, of course.

Related

Store math operator in variable

I am creating an application in C# MVVM. I have a simple question. Is there any possibility to store math operator in variable? I have a code like that:
public ICollectionView FilteredCollection
{
get
{
return filteredCollection;
}
set
{
filteredCollection = value;
OnPropertyChanged("FilteredCollection");
}
}
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary == Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
);
What I want to achieve:
In fourth line (DynamicSearchEmployeeSalary) math operator should be depended on following conditions:
if (IsPressedEqual == true)
VARIABLE = "=="
if (IsPressedLess == true)
VARIABLE = "<"
if (IsPressedGreater == true)
VARIABLE = ">"
if (IsPressedLess == true && IsPressedEqual == true)
VARIABLE = "<="
if (IsPressedGreater == true && IsPressedEqual == true)
VARIABLE = ">="
Scenario:
For example I put a value like 10000 in textbox, then click on button with "=" operator. As a result I want to receive Employees with Salary equals than 10000.
Then I click on ">". And I have Employees with Salary greater and equals 10000.
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || ((Employee)x).EmployeeSalary VARIABLE Convert.ToInt32(DynamicSearchEmployeeSalary))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
I've made a simple Rule Based Engine ... I think it will help you in your issue ...
please find it as a nuget package here: https://www.nuget.org/packages/IbnSherien.RuleBasedEngine/
you can create a rule like this:
var rule = RuleEngine.CreateRule<Employee>()
.If<Employee>(e => e.EmployeeSalary).GreaterThan(DynamicSearchEmployeeSalary)
.Validate();
FilteredCollection.Filter = x => (
(string.IsNullOrEmpty(DynamicSearchEmployeeName) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeName))
&& (DynamicSearchEmployeeID == null || ((Employee)x).EmployeeID == DynamicSearchEmployeeID)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeSalary) || rule.Match((Employee)x).IsMatch)
&& (string.IsNullOrEmpty(DynamicSearchEmployeeDesigner) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeDesigner))
&& (string.IsNullOrEmpty(DynamicSearchEmployeeEmailID) || ((Employee)x).EmployeeName.Contains(DynamicSearchEmployeeEmailID))
feel free to add any comments or contribute to the package

How do I get Linq to return identical repeated rows only once?

I'm still pretty new to this, so go easy on me. I'm trying to get linq to return a single record when the query returns multiple identical records. Here's what I have:
var query = (from i in _db.BizListView
let dist = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog)) * .0006214
where
dist <= rng &&
i.Name.Contains(key) &&
pri != -1 ? (i.BizCategoryID == pri && i.Primary == true) : true &&
biz != -1 ? (i.BizCategoryID == biz) : true
group i by new
{
ClientID = i.ClientID,
Name = i.Name,
Address = i.Address,
Address1 = i.City + ", " + i.StateID + " " + i.PostCode,
BizPhone = i.BizPhone,
EmailAddress = i.EmailAddress,
ClientImagePath = i.ClientImagePath,
Distance = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog)) * 0.0006214
}
into myTable
orderby myTable.Key.Distance ascending
select new
{
ClientID = myTable.Key.ClientID,
Name = myTable.Key.Name,
Address = myTable.Key.Address,
Address1 = myTable.Key.Address1,
BizPhone = myTable.Key.BizPhone,
EmailAddress = myTable.Key.EmailAddress,
ClientImagePath = myTable.Key.ClientImagePath,
Distance = myTable.Key.Distance
}).Distinct();
return query;
The query produces a single record for each client, as long as a BizCategory is specified, but returns multiple identical records per client (a record for each of the Client's BizCategories) if no BizCategory is specified. How can I get the query to return a single record per client, instead of multiple identical records when no BizCategory is specified?
I believe that operator precedence is affecting the query.
Try adding parentheses around the ternary operators.
(pri != -1 ? (i.BizCategoryID == pri && i.Primary == true) : true) &&
(biz != -1 ? (i.BizCategoryID == biz) : true)
A simpler way to express this condition could be:
(pri == -1 || i.BizCategoryID == pri) &&
(biz == -1 || i.BizCategoryID == biz)
The way it was interpreted:
pri != -1
? (i.BizCategoryID == pri && i.Primary == true)
: (true && (biz != -1 ? (i.BizCategoryID == biz) : true))
|< ----- IGNORED ----------------------------->|
You can see that the true && biz != -1... took precedence here. As true was evaluated first, the biz was never evaluated.
Gah!! All I had to do was add an additional conditional!
var query = from i in _db.BizListView
let dist = DbGeography.FromText(i.Point).Distance(DbGeography.FromText(geog)) * 0.0006214
where
dist <= rng &&
i.Name.Contains(key) &&
pri != -1 ? (i.BizCategoryID == pri && i.Primary == true) : true &&
biz != -1 ? (i.BizCategoryID == biz) : true &&
(biz == -1 && pri == -1) ? (i.Primary == true): true
orderby i.Distance ascending
select i;
Oh well. Live and learn.

How can I return a bool value from a plethora of nullable bools?

With this code:
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked) ||
(ckbx2.IsChecked) ||
(ckbx3.IsChecked) ||
(ckbx4.IsChecked));
}
...I'm stopped dead in my tracks with
Operator '||' cannot be applied to operands of type 'bool?' and 'bool?
So how do I accomplish this?
You can chain together |s, using the null-coalescing operator at the end:
return (ckbx1.IsChecked | cxbx2.IsChecked | cxbx3.IsChecked | cxbx4.IsChecked) ?? false;
The lifted | operator returns true if either operand is true, false if both operands are false, and null if either operand is null and the other isn't true.
It's not short-circuiting, but I don't think that'll be a problem for you in this case.
Alternatively - and more extensibly - put the checkboxes into a collection of some kind. Then you can just use:
return checkboxes.Any(cb => cb.IsChecked ?? false);
Try:
return ((ckbx1.IsChecked ?? false) ||
(ckbx2.IsChecked ?? false) ||
...
I'm assuming that if null, then it'll be false, you can use the ?? operator.
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked ?? false) ||
(ckbx2.IsChecked ?? false) ||
(ckbx3.IsChecked ?? false) ||
(ckbx4.IsChecked ?? false));
}
You can use GetValueOrDefault() to get either the value, or false.
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked.GetValueOrDefault()) ||
(ckbx2.IsChecked.GetValueOrDefault()) ||
(ckbx3.IsChecked.GetValueOrDefault()) ||
(ckbx4.IsChecked.GetValueOrDefault()));
}
You can use the following:
(ckbx1.IsChecked.HasValue && ckbx1.IsChecked.Value)
Use ?? operator inside your method;
private bool AtLeastOnePlatypusChecked()
{
return ((ckbx1.IsChecked ?? false) ||
(ckbx2.IsChecked ?? false) ||
(ckbx3.IsChecked ?? false) ||
(ckbx4.IsChecked ?? false)
}

if statement, boolean value

This method is taken from Murach's C# 2010 book and is given as an example of an method that checks if a string contains a decimal value:
// the new IsDecimal method
public bool IsDecimal(TextBox textBox, string name)
{
//make sure the string only contains numbers and numeric formatting
string s = textBox.Text;
int decimalCount = 0;
bool validDecimal = true;
foreach (char c in s)
{
if (!(
c == '0' || c == '1' || c == '2' || // numeric chars
c == '3' || c == '4' || c == '5' ||
c == '6' || c == '7' || c == '8' ||
c == '9' || c == '.' ||
c == '$' || c == '%' || c == ',' || // formatting chars
c == ' '
))
{
validDecimal = false;
break;
}
if (c == '.')
{
decimalCount++;
}
} // end loop
if (validDecimal && decimalCount <= 1)
{
return true;
}
else
{
MessageBox.Show(name + " must be a decimal number.",
"Entry Error");
textBox.Focus();
return false;
}
}
My question is about this if statement and boolean value:
if (validDecimal && decimalCount <= 1)
{
return true;
}
I understand that it should be checking if both validDecimal returns true from above loop and that there is only one decimal point present. I'm quite confused by this, my understanding of bool is that it can hold two values: 1 = true and 0 = false; in both of those cases that if statement would be satisfied (0 is smaller than 1 and 1 is equal). I'm thinking that correct if statement would look something like that: if (validDecimal == true && decimalCount <= 1) but since I'm beginner I'm not sure and this isn't in the errata for this book.
A bool value on its own is the same as value == true
If you have
bool trueThing = true;
then the following are all equivalent (and true)
trueThing;
trueThing == true;
(trueThing == true) == true;
((trueThing == true) == true) == true;
and so on. The simplest, least verbose form is the first: trueThing. It's not a 0 or 1, it's a true or false.
Operator Precedence. This:
if (validDecimal && decimalCount <= 1)
is interpreted as:
if (validDecimal && (decimalCount <= 1))
not
if ((validDecimal && decimalCount) <= 1)
In other words, the <= happens before the &&.
I think you're reading the statement wrong, if you placed parentheses, so that it's obvious what's going on, it would look like
(validDecimal) && (decimalCount <= 1)
not
(validDecimal && decimalCount) <= 1
In English: check that validDecimal is true and decimalCount is at most 1. The comparison against true is implicit, because it's not necessary.
In C#, variable of type bool can have one of two values, true or false, but they don't act as numbers, so you can't say they are 1 and 0 (although they are usually implemented that way).
Also, in most languages, if you mean “a and b are both at most x”, you can't write it as a && b <= x. That's just not how (most) computer languages work.
You can write
if (validDecimal == true && decimalCount <= 1)
but it is equivalent to the shorthand way
if (validDecimal && decimalCount <= 1)
When the type is a bool no need to again use
== true
as it is assumed
I don't really know in c#, but in Java, you can even do this:
boolean b = 1<2;
1<2 is true (remember, it's a boolean equation), so the value assigned to b is true. Everything you put in the if, is interpreted as
if(whateverLogicEquationHereIsTrue){do this}
else{means that the boolean input to the if, has come to be false}
now, what is the output of this?
if(!(1>2)){print "a"}
else{print "b"}
hint: ! is the logical operator NOT

Cycle in C# can't get this to end >.<

Right now I'm trying to make it so I've got 1 character and 3 enemies if my character dies it's supposed to give game over or something but I can't make it to work (if enemies die it works tho I don't know why).
Here is what I'm doing:
bool Exit = false;
bool CharDead = false;
Heroe Heroe1 = p.ElementAt(0);
Enemigo Enemigo1 = l.ElementAt(0);
Enemigo Enemigo2 = l.ElementAt(1);
Enemigo Enemigo3 = l.ElementAt(2);
a.Agregar(comienza);
List<Items> item = new List<Items>();
do
{
if (Heroe1.HP > 0)
AccionesHeroe1(l, p);
if (Enemigo1.HP > 0)
AccionesEnemigo1(l, p);
if (Enemigo2.HP > 0)
AccionesEnemigo2(l, p);
if (Heroe1.HP > 0)
AccionesHeroe1(l, p);
else
CharDead = true;
if (Enemigo3.HP > 0)
AccionesEnemigo3(l, p);
if (Heroe1.HP <= 0)
{
CharDead = true;
}
if (Enemigo1.HP <= 0 && Enemigo2.HP <= 0 && Enemigo3.HP <= 0)
{
Exit = true;
}
} while (Exit == false || CharDead == false);
Your ending condition is:
(Exit == false || CharDead == false);
This will only exit when CharDead AND Exit are both true.
You probably want to rework it to be:
(Exit == false && CharDead == false);
This way, as soon as Exit is not false or CharDead is not false, you'll exit.
I think you want to change your while loop expression to
do
{
} while(!Exit && !CharDead)
change
while (Exit == false || CharDead == false);
to
while (Exit == false && CharDead == false);
This would work too, right?
while(!(Exit || CharDead));

Categories