What is the best way to re-write the same logic? - c#

if ((ddl1.SelectedValue == "1") || (ddl1.SelectedValue == "100"))
{
if (Fee > 0)
{
Messages += " [Please the check fee and ddl1 type selected] ";
}
}
else if ((ddl1.SelectedValue == "2") || (ddl1.SelectedValue == "200"))
{
if (Fee == 0)
{
Messages += " [Please the check fee and ddl1 type selected] ";
}
}
//How to re-write the same logic in the most concise way?

if (((ddl1.SelectedValue == "1" || ddl1.SelectedValue == "100") && Fee > 0) ||
((ddl1.SelectedValue == "2" || ddl1.SelectedValue == "200") && Fee == 0 ))
{
Messages += " [Please the check fee and ddl1 type selected] ";
}
The innermost the parentheses are optional and for clarify to the reader and not compilation.
If you are absolutely certain that SelectedValue will never be anything other than 1, 100, 2 or 200, you can further consolidate (ddl1.SelectedValue == "1" || ddl1.SelectedValue == "100") to ddl1.SelectedValue.StartsWith("1"). If selected values contains other values or is total domain is subject to change, StartsWith becomes fragile.

string[] ValidValues = {"1", "100", "2", "200"};
if(Fee >= 0){
Messages += Array.IndexOf(ValidValues, ddl1.SelectedValue) == -1 ? "" : " [Please the check fee and ddl1 type selected] ";
}

Related

To convert if condition to linq in cshtml

Code
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
}
}
I have tried the following code and unable to complete it fully as expected
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where((a => a.CurrentStatus == 1 || a.CurrentStatus == 2)
&& )
})
How to convert the above if condition to linq in cshtml. Thanks
the else-if relationship is an OR relationship. So simply combine the two lines. the inner nested if inside the else if is an AND relationship. This would go into the second set of parentheses
Collection = Model.Collection.Where
(
(a => a.CurrentStatus == 1 || a.CurrentStatus == 2) ||
((a.CurrentStatus == 3 || a.CurrentStatus == 4) && a.Date != null && a.Date <= 30)
)
EDIT:
Here is another suggestion: extract the readable code into an own method that evaluates the condition and returns the boolean result. This way you can make a predicate that can be accepted by the Where method:
private bool IsForDisplay( ModelDataType Model )
{
if(Model.CurrentStatus == 1 || Model.CurrentStatus == 2)
{
//can display those records..
return true;
}
else if((Model.CurrentStatus == 3 || Model.CurrentStatus == 4) && Model.Date != null)
{
if(Model.Date <= 30 days)
{
//can display those records..
return true;
}
}
return false;
}
now you can use it simply in the linq expression:
#Html.Partial("Filter", new IndexModel()
{
Id = Model.Id,
Collection = Model.Collection.Where(a => IsForDisplay(a))
});

Modify IList Query Statement

I have the following statement, and I want to modify it to not select all tables.
Exclude 2 columns customerItemNo and manufacturerItemNo in the if, and
Exclude 2 columns customerItemNoAppend and manufacturerItemNoAppend in the else if.
How can I do it?
if (p.UserInternal == 'Y' && p.UserActive == 'Y')
inventorySummary = DataProvider.SelectCondition<Q_TBL_INVENTORY_SUMMARY>
(r => r.InventoryLocationNo == location);
else if (p.UserInternal != 'Y' && p.UserActive == 'Y')
inventorySummary = DataProvider.SelectCondition<Q_TBL_INVENTORY_SUMMARY>
(r => r.InventoryLocationNo == location && (r.CustomerID == customerID || r.CustomerID == " "));
else
inventorySummary = new List<Q_TBL_INVENTORY_SUMMARY>();

IF condition AND / OR logic fails - c# [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have 2 combobox and 7 textboxes.
The logic if the user provides input as 0 in all the textboxes and has selected the Leave or Holiday in the combox box then the condition should satisfy.
If they selected someother item in the combo box apart from the Holiday/Leave. It should throw the else part.
I have written below condition in c# but eventhough all the conditions are satisfied the code executes only the else condition.
if (((comboBox3.SelectedText == "Leave") ||
(comboBox3.SelectedText == "Holiday")) &&
textBox2.Text != "0" &&
textBox3.Text != "0" &&
textBox4.Text != "0" &&
textBox5.Text != "0" &&
textBox6.Text != "0" &&
textBox7.Text != "0" &&
textBox10.Text != "0")
{
MessageBox.Show("Sucess");
}
else
{
MessageBox.Show("Select Leave/Holiday since all the provided Data is 0");
}
EDIT:
As per the request, the output is:
State
0
0
0
0
0
0
0
Try this
if (((comboBox3.SelectedText == "Leave") ||
comboBox3.SelectedText == "Holiday")) &&
textBox2.Text == "0" &&
textBox3.Text == "0" &&
textBox4.Text == "0" &&
textBox5.Text == "0" &&
textBox6.Text == "0" &&
textBox7.Text == "0" &&
textBox10.Text == "0")
{
MessageBox.Show("Sucess");
}
else
{
MessageBox.Show("Select Leave/Holiday since all the provided Data is 0");
}
Replace your code with this and add the result from the Output window/MessageBox to your question above
if (((comboBox3.SelectedText == "Leave") ||
comboBox3.SelectedText == "Holiday")) &&
textBox2.Text == "0" &&
textBox3.Text == "0" &&
textBox4.Text == "0" &&
textBox5.Text == "0" &&
textBox6.Text == "0" &&
textBox7.Text == "0" &&
textBox10.Text == "0")
{
MessageBox.Show("Success");
}
else
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("State");
sb.AppendLine(comboBox3.SelectedText);
sb.AppendLine(textBox2.Text);
sb.AppendLine(textBox3.Text);
sb.AppendLine(textBox4.Text);
sb.AppendLine(textBox5.Text);
sb.AppendLine(textBox6.Text);
sb.AppendLine(textBox7.Text);
sb.AppendLine(textBox10.Text);
Console.WriteLine(sb.ToString());
MessageBox.Show(sb.ToString());
}
Ok. You're using combobox1.SelectedText, which is empty!
Try using combobox1.Text instead ...
if (((comboBox3.Text == "Leave") ||
comboBox3.Text == "Holiday")) &&
textBox2.Text == "0" &&
textBox3.Text == "0" &&
textBox4.Text == "0" &&
textBox5.Text == "0" &&
textBox6.Text == "0" &&
textBox7.Text == "0" &&
textBox10.Text == "0")
{
MessageBox.Show("Success");
}
else
{
MessageBox.Show("Select Leave/Holiday since all the provided Data is 0");
}
As mentioned by the user "dasblinkenlight", your code, in the actual state, translate as:
"If the user select Leave or Holiday and ALL inputs are DIFFERENT than 0, then 'Success'."
But your business logic state that "If the user select Leave or Holiday and ALL inputs are EQUAL than 0, then 'Success'".
Just change the "!=" operator for the "==" operator and you are fine.

1 Button 4 Comboboxes On Win Form

I have 1 button that will execute a stored procedure based off which combobox has data in it. Are multiple if statements the best course for me to account for each combobox scenario? I currently have my code like so - which works, but is a bit slow. Is there a better way to write this syntax using C# and VS2013?
private void btn1_Click()
{
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
{
MessageBox.Show("You failed to make a selection.");
return;
}
if (cbo1.Text.ToString() != "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
{
//Go route1
}
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() 1= "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() == "" )
{
//Go route2
}
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() != "" && cbo4.Text.ToString() == "" )
{
//Go route3
}
if (cbo1.Text.ToString() == "" && cbo2.Text.ToString() == "" && cbo3.Text.ToString() == "" && cbo4.Text.ToString() != "" )
{
//Go route4
}
}
EDIT
#MethodMan --> is this how you would go about setting up the check?
var comboBoxes = this.Controls
.OfType<ComboBox>()
.Where(x => x.Name.StartsWith("comboBox"));
foreach(var cmbBox in comboBoxes)
{
(string.IsNullOrEmpty(cmbBox.Text)) || if (cmbBox.SelectedIndex == -1)
{
//How to find which combobox is cmbBox
}
}
my suggestion will be something like this:
private void btn1_Click()
{
int data = 0;
if(cbo1.Text.ToString() != "")
data+=1;
if(cbo2.Text.ToString() != "")
data+=2;
if(cbo3.Text.ToString() != "")
data+=4;
if(cbo4.Text.ToString() != "")
data+=8;
switch(data)
{
case 1:
//Go route1
break;
case 2:
//Go route2
break;
case 4:
//Go route3
break;
case 8:
//Go route4
break;
default:
MessageBox.Show("You failed to make a selection.");
break;
}
}
i`m not sure it will do the job you want but it is a lot faster and this way you can check wich combo the user selected and wich combo he did not

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.

Categories