evaluation of conditions in an if statement - c#

Suppose I have this if statement:
foreach (MyModel m in SomeList)
{
if (m.pID != SomeValue && (m.xID != 0 && SomeFunction(m.xID) == false)
{
return false;
}
}
I only want SomeFunction(m.xID) == false to evaluate if m.xID != 0 so if m.xID == 0 then don't evaluate SomeFunction
For the moment, I have this if statement broken down into 2 statements and I'm looking to see how I can combine these into just one while preserving the logic. This is the original:
foreach (MyModel m in SomeList)
{
if (m.xID != 0 && SomeFunction(m.xID) == false)
{
return false;
}
if (m.pID != SomeValue)
{
return false;
}
}

If that is all your loop is doing then I would be inclined to remove the loop entirely.
Also, instead of comparing something to false, just use the ! operator.
if (SomeList.Any(MyModel m=>m.xID != 0 && !SomeFunction(m.xID) || m.pID != SomeValue))
return false;

you are looking for this || Operator (C# Reference)
if ((m.xID != 0 && SomeFunction(m.xID) == false) || (m.pID != SomeValue))
{
return false;
}

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))
});

How to overcome foreach loop for list object dynamically

I'm swapping my values in List Object on some conditions and update List Object value.
Currently, what I'm doing is
- Looping on each object through List
- Check If condition is net
- Swap values
public static void SwapMinMaxIfNull<T>(this IEnumerable<T> rows, string reportfor)
{
if (reportfor.Equals("Comparison"))
{
var row = rows as IEnumerable<RiskBoardDataToExport>;
try
{
if (rows.Any())
{
var Tests = row.Where(min => min.MinGaitSpeed == null && min.MaxGaitSpeed != null).ToList();
if (Tests != null)
{
foreach (RiskBoardDataToExport test in Tests)
{
test.MinGaitSpeed = test.MaxGaitSpeed;
test.MaxGaitSpeed = null;
}
}
// again check for next object
Tests = row.Where(min => min.MinTUGTime == null && min.MaxTUGTime != null).ToList();
if (Tests != null)
{
foreach (RiskBoardDataToExport test in Tests)
{
test.MinTUGTime = test.MaxTUGTime;
test.MaxTUGTime = null;
}
}
// again check for next object
Tests = row.Where(min => min.MinBergScoreSpeed == null && min.MaxBergScoreSpeed != null).ToList();
if (Tests != null)
{
foreach (RiskBoardDataToExport test in Tests)
{
test.MinBergScoreSpeed = test.MaxBergScoreSpeed;
test.MaxBergScoreSpeed = null;
}
}
//.. for brevity
}
}
}
Can I do it in better way? I know about PropertyInfo i.e. Can check property name and get value etc, but, not having any hint to get this done.
Thanks
It's not exactly what you're asking for, but you can combine the clauses in your Where statements and then have a few if statements in the body:
public static void SwapMinMaxIfNull(this IEnumerable<RiskBoardDataToExport> rows,
string reportfor)
{
if (rows = null) return;
if (reportfor.Equals("Comparison", StringComparison.OrdinalIgnoreCase))
{
foreach (var row in rows.Where(r =>
(r.MinGaitSpeed == null && r.MaxGaitSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null)))
{
if (row.MinGaitSpeed == null)
{
row.MinGaitSpeed = row.MaxGaitSpeed;
row.MaxGaitSpeed = null;
}
if (row.MinTUGTime == null)
{
row.MinTUGTime = row.MaxTUGTime;
row.MaxTUGTime = null;
}
if (row.MinBergScoreSpeed == null)
{
row.MinBergScoreSpeed = row.MaxBergScoreSpeed;
row.MaxBergScoreSpeed = null;
}
}
}
}
As this is an operation where order of the items in the list does not matter, you can easily speed this up by parallelization (you can read up on that here).
So, what you should do, is handle this foreach loop in a parallel way and combine it with Rufus L's optimized code for the fastest result.
var rows = rows.Where(r =>
(r.MinGaitSpeed == null && r.MaxGaitSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null) ||
(r.MinBergScoreSpeed == null && r.MaxBergScoreSpeed != null))
Parallel.ForEach(rows, (row) => {
{
if (row.MinGaitSpeed == null)
{
row.MinGaitSpeed = row.MaxGaitSpeed;
row.MaxGaitSpeed = null;
}
if (row.MinTUGTime == null)
{
row.MinTUGTime = row.MaxTUGTime;
row.MaxTUGTime = null;
}
if (row.MinBergScoreSpeed == null)
{
row.MinBergScoreSpeed = row.MaxBergScoreSpeed;
row.MaxBergScoreSpeed = null;
}
}
Note that this requires the System.Threading.Tasks namespace, that's where the Parallel class is.

Any way to further reduce the number of lines of code?

I'm looking for ways to reduce the number of lines of code for this function. Any help is appreciated!
private bool CanSubmitPackage ( object obj )
{
// ---- Checks if the package contains any files to be submitted ----
if ( _selectedWorkspace.Package.Files != null )
{
if ( _selectedWorkspace.Package.Files.Count > 0 )
if ( _selectedWorkspace.Package.Platform != null || _selectedWorkspace.Package.Platform != "" )
if ( _selectedWorkspace.Package.PackagePath != null || _selectedWorkspace.Package.PackagePath != "" )
if ( _selectedWorkspace.Package.PackageSize != null || _selectedWorkspace.Package.PackageSize != "" )
if ( _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "" )
return true;
else
return false;
else
return false;
else
return false;
else
return false;
else
return false;
}
else
return false;
}
return ( _selectedWorkspace.Package.Files?.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
You can make it shorter and readable by using && operator and string.IsNullOrEmpty method:
return ( _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
If you're using c#6+, then you can go further (just a little bit) and use Expression Bodied method:
private bool CanSubmitPackage () => //I'm not sure about object obj argument
( _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
If you are going after making your code text shorted, you can declare a short named variable and use that instead of _selectedWorkspace.Package:
var p = _selectedWorkspace.Package;
return (p.Files?.Count > 0
&& !string.IsNullOrEmpty(p.Platform)
&& !string.IsNullOrEmpty(p.PackagePath)
&& !string.IsNullOrEmpty(p.PackageSize)
&& !string.IsNullOrEmpty(p.SubmittedBy));;
This is one way to do it
Update
return ( _selectedWorkspace != null
&& _selectedWorkspace.Package != null
&& _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackagePath)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.PackageSize)
&& !string.IsNullOrEmpty(_selectedWorkspace.Package.SubmittedBy));
Old Ans
return ( _selectedWorkspace.Package.Files != null
&& _selectedWorkspace.Package.Files.Count > 0
&& ( _selectedWorkspace.Package.Platform != null || _selectedWorkspace.Package.Platform != "" )
&& ( _selectedWorkspace.Package.PackagePath != null || _selectedWorkspace.Package.PackagePath != "" )
&& ( _selectedWorkspace.Package.PackageSize != null || _selectedWorkspace.Package.PackageSize != "" )
&& ( _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "" ));
This is another way to do it
private bool CanSubmitPackage(object obj)
{
// ---- Checks if the package contains any files to be submitted ----
if (_selectedWorkspace.Package.Files == null) return false;
if (_selectedWorkspace.Package.Files.Count <= 0) return false;
if (_selectedWorkspace.Package.Platform == null && _selectedWorkspace.Package.Platform == "") return false;
if (_selectedWorkspace.Package.PackagePath == null && _selectedWorkspace.Package.PackagePath == "") return false;
if (_selectedWorkspace.Package.PackageSize != _selectedWorkspace.Package.PackageSize != "")
return _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "";
return false;
}
I would prefer #xneg's answer (https://stackoverflow.com/a/53096740/10588170), however, you could also drop all 'else' Statements and replace them with a single return statement after the 'if'-block.
Make sure to use string.IsNullOrEmpty(_str) in future, or you have to use && instead of ||, otherwise you will get an Exception because you are checking if _str is empty if it is null and if it is not null, you are not checking the content of _str at all. I am pretty sure that that's not what you wanna do.
I would maybe split the conditions, for example:
public bool HasFile
{
get { return _selectedWorkspace.Package.Files != null && _selectedWorkspace.Package.Files.Count > 0; }
}
public bool HasPlatform
{
get { return !string.IsNullOrEmpty(_selectedWorkspace.Package.Platform); }
}
// Do that for all conditions
And then you can write your final if like this:
bool result = HasFile && HasPlatform && …
If you wanted to keep it largely the same, as the return for all of your IF statements failing is false, you only need to include it once. If any of your current checks fail, it won't be able to execute "return true", so you can just have one final return statement like this:
private bool CanSubmitPackage ( object obj )
{
// ---- Checks if the package contains any files to be submitted ----
if ( _selectedWorkspace.Package.Files != null )
if ( _selectedWorkspace.Package.Files.Count > 0 )
if ( _selectedWorkspace.Package.Platform != null || _selectedWorkspace.Package.Platform != "" )
if ( _selectedWorkspace.Package.PackagePath != null || _selectedWorkspace.Package.PackagePath != "" )
if ( _selectedWorkspace.Package.PackageSize != null || _selectedWorkspace.Package.PackageSize != "" )
if ( _selectedWorkspace.Package.SubmittedBy != null || _selectedWorkspace.Package.SubmittedBy != "" )
return true;
// One of the above checks failed, that's why we're running this line
return false;
}
I also prefer #xneg, #SeM, or #Mihir Dave's approach (as they're all basically the same answer), but it does come down to what you find most comfortable / readable. I would definitely use the method String.IsNullOrEmpty() to simplify your if statements however.
Additionally, what the ? does in xneg's answer: _selectedWorkspace.Package.Files?.Count is say "If Files is not null, retrieve Files.Count, otherwise return null. Then in C# a statement like, null > 0 always returns false.

Can't get the correct Bool result in C#

I have a form where I would like to check for validation before processing the form. My form has 2 sections so I want to make sure that at least one item from each section is selected when they press submit button, and if they did then go to Dashboard.aspx. Even if I put all the required info when it checks for result1 and result2, I get false. Result1 and Result2 won't get the correct value. Even if the values are True again it passes false.
Here is my code:
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
bool result1 = false;
bool result2 = false;
CheckWireFromValidation(result1);
CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation (bool result1)
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
result1 = true;
}
else
{
result1 = false;
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
}
return result1;
}
public bool CheckWireToValidation(bool result2)
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
result2 = true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
}
return result2;
}
You're not using the results of CheckWireToValidation. You're using the false value you allocate initially.
Try this
bool result1 = false;
bool result2 = false;
if (CheckWireFromValidation(result1) && CheckWireToValidation(result2))
{
Response.Redirect("~/DashBoard.aspx");
}
Edit
The behavior you're expecting is that of the out parameter modifier. But please don't write code that way ...
I edited your code to get rid of .. em .. cruft. This should be more readable.
protected void btnSumbit_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
return;
if (CheckWireFromValidation() && CheckWireToValidation())
{
Response.Redirect("~/DashBoard.aspx");
}
}
public bool CheckWireFromValidation ()
{
if (drpFromCoporate.SelectedIndex != 0 || drpFromCapital.SelectedIndex != 0 || drpFromProperty.SelectedIndex != 0)
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire From drop downs!!");
return false;
}
}
public bool CheckWireToValidation ()
{
if (drpToCapital.SelectedIndex != 0 || drpToCoporate.SelectedIndex != 0 || drpToProperty.SelectedIndex != 0 || drpToTemplate.SelectedIndex != 0 || txtCorpAmt.Text != "" || txtCapAmt.Text != "" || txtPropAmt.Text != "" || txtTempelateAmt.Text != "")
{
return true;
}
else
{
ShowAlertMessage("You need to choose at least one filed from Wire To drop downs!!");
return false;
}
}
Since you are passing Result1 and Result2 in as parameters instead assigning them. The results will never be set.
Here's one correct way of doing this
bool result1 = CheckWireFromValidation(result1);
bool result2 = CheckWireToValidation(result2);
if (result1 == true && result2 == true)
{
Response.Redirect("~/DashBoard.aspx");
}
and also a side note. I think we can safely remove the boolean parameter from the CheckWireFromValidation methods. Since the return value doesn't depends on the input variable.
Hope this helps.

How to break if-else-if using C#

How do I break if-else-if.....Why its not working? its just checking all the conditions instead of performing the tasks. following is my code. I have checked it through breakpoints its moving to all conditions why it doesn't get stop after meeting the correct condition. even it is not going into the if activity it just read all the conditions and do nothing at the end.
private void ShowHash()
{
inpic = pb_selected.Image;
Bitmap image = new Bitmap(inpic);
byte[] imgBytes = new byte[0];
imgBytes = (byte[])converter.ConvertTo(image, imgBytes.GetType());
string hash = ComputeHashCode(imgBytes);
txt_selectedText.Text = hash;
GetHash();
}
private void GetHash()
{
if (txt_sel1.Text == null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null ))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != null && (txt_sel2.Text == null || txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (txt_sel2.Text != null && (txt_sel3.Text == null || txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (txt_sel3.Text != null && (txt_sel4.Text == null || txt_sel5.Text == null))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (txt_sel4.Text != null && (txt_sel5.Text == null))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
}
I strongly suspect the problem is that the Text property is never null for any of txt_sel*. Assuming these are text boxes in a UI, it's much more likely that if there's no text in the text box, the Text property will return "" instead of null. That's the way most UI frameworks handle empty controls.
I would also suggest extracting the conditions into local variables first:
bool hasSel1 = txt_sel1.Text != "";
bool hasSel2 = txt_sel2.Text != "";
bool hasSel3 = txt_sel3.Text != "";
bool hasSel4 = txt_sel4.Text != "";
bool hasSel5 = txt_sel5.Text != "";
if (!hasSel1 && (!hasSel2 || !hasSel3 || !hasSel4 || !hasSel5)
{
...
}
And ideally, give your controls more meaningful names - a collection of variables with the same prefix but then a numeric suffix is very rarely a good idea, in terms of readability.
Reason:
If there is nothing in those textboxes, textbox.Text will return an empty string ("") not null.
Solution:
Check against "" not null:
private void GetHash()
{
if (txt_sel1.Text == "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (txt_sel1.Text != "" && (txt_sel2.Text == "" || txt_sel3.Text == "" || txt_sel4.Text == "" || txt_sel5.Text == ""))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
....
....
EDIT: You don't have to do ==true for boolean variables. If statement checks it against true by default. Use ! to check against false:
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || hasValue2 || hasValue4 || hasValue5))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
....
....
I think for string better to use inbuild null and whitespace check function:
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2= string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3= string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4= string.IsNullOrWhiteSpace((txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
And then define if condition on these bool. This case can handle unexpected null or white space values.
That is bacause it probably doesn't find any of those conditions true.
If it would find a true condition it would execute that if block and won't event check the others.
To add to what others have said, you should really have a final else statement in there to catch issues such as this:
else
{
throw new InvalidOperationException("My If Statement is Broken");
}
Thanks to you all! My problem is solved by changing the conditions and your suggested alteration, following is the code may be helped some beginner like me.
private void GetHash()
{
bool hasValue1 = string.IsNullOrWhiteSpace(txt_sel1.Text);
bool hasValue2 = string.IsNullOrWhiteSpace(txt_sel2.Text);
bool hasValue3 = string.IsNullOrWhiteSpace(txt_sel3.Text);
bool hasValue4 = string.IsNullOrWhiteSpace(txt_sel4.Text);
bool hasValue5 = string.IsNullOrWhiteSpace(txt_sel5.Text);
if (hasValue1 && (hasValue2 || hasValue3 || hasValue4 || hasValue5))
{
txt_sel1.Text = txt_selectedText.Text;
return;
}
else if (hasValue2 && (!hasValue1 ||hasValue3 || hasValue4 || hasValue5 ))
{
txt_sel2.Text = txt_selectedText.Text;
return;
}
else if (hasValue3 && (!hasValue1 || !hasValue2 || hasValue4 || hasValue5 ))
{
txt_sel3.Text = txt_selectedText.Text;
return;
}
else if (hasValue4 && (!hasValue1 || !hasValue2 || !hasValue3 || hasValue5 ))
{
txt_sel4.Text = txt_selectedText.Text;
return;
}
else if (hasValue5 && (!hasValue1 || !hasValue2 || !hasValue3 || !hasValue4 ))
{
txt_sel5.Text = txt_selectedText.Text;
return;
}
else
{
CompareHash();
}
}

Categories