Optimize if -else statement Ask [closed] - c#

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 4 years ago.
Improve this question
I have below if-else statement, and I want to optimize it more.
Is there any way to optimize it more
if(entity[attributeName] != null)
{
if (entity.FormattedValues.Contains(attributeName) && entity[attributeName].GetType() != typeof(EntityReference))
{
return entity.FormattedValues[attributeName];
}
else
{
return GetDisplayObjectFromRawValue(entity[attributeName]);
}
}
else
{
if (entity.FormattedValues.Contains(attributeName))
{
return entity.FormattedValues[attributeName];
}
else
{
return GetDisplayObjectFromRawValue(entity[attributeName]);
}
}

If it's just for length of code, you could rewrite it like so:
if (entity.FormattedValues.Contains(attributeName)
&& (entity[attributeName] == null || entity[attributeName].GetType() != typeof(EntityReference)))
{
return entity.FormattedValues[attributeName];
}
else
{
return GetDisplayObjectFromRawValue(entity[attributeName]);
}
Or expressed as a ternary statement:
return entity.FormattedValues.Contains(attributeName)
&& (entity[attributeName] == null || entity[attributeName].GetType() != typeof(EntityReference))
? entity.FormattedValues[attributeName]
: GetDisplayObjectFromRawValue(entity[attributeName]);
I've simplified your original code down to boolean values in an example here:
v1 (entity[attributeName] != null),
v2 (entity.FormattedValues.Contains(attributeName))
v3 (entity[attributeName].GetType() != typeof(EntityReference))
Note that you should generally write your code in a way that promotes legibility over brevity.

If I understand you mean correctly, your code can be rewritten like this:
if(entity[attributeName] != null)
{
return entity.FormattedValues.Contains(attributeName) && entity[attributeName].GetType() != typeof(EntityReference)
? entity.FormattedValues[attributeName]
: GetDisplayObjectFromRawValue(entity[attributeName]);
}
return entity.FormattedValues.Contains(attributeName)
? entity.FormattedValues[attributeName]
: GetDisplayObjectFromRawValue(entity[attributeName]);
P/S: This way has nothing to do with: it made the code run faster or it saves memory while running or something like that. Just for readability.

Related

C# nicer way of writing if statement with two values [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 2 years ago.
Improve this question
I was wondering if anyone could please tell me a nicer way of writing this. These are the only conditions that are used.
private static void BondedNonBoundedIndicator(InvoiceLine invoiceLine, Product packageProduct)
{
var value = packageProduct.BondedQuantity;
var value2 = packageProduct.NonBondedQuantity;
if (value == 0 && value2 == 1)
{
invoiceLine.BondedORBbondedIndicator = "N";
}
if (value == 1 && value2 == 0)
{
invoiceLine.BondedORBbondedIndicator = "Y";
}
}
Using C# 8, we can use tuples and the switch expression to simplify this:
invoiceLine.BondedORBbondedIndicator = (value, value2) switch {
(0, 1) => "N",
(1, 0) => "Y",
_ => invoiceLine.BondedORBbondedIndicator
};
You could shorten the last case even further if you know the invoiceLine.BondedORBbondedIndicator before the code is run is always, say ""(, then the last case would be _ => "").
You can use xor logic
If(value1^value2 == 1)
value1 == 0 ? invoiceLine.BondedORBbondedIndicator = "N" : invoiceLine.BondedORBbondedIndicator = "Y";

GUI optimize nested foreach [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 4 years ago.
Improve this question
Can anyone assist on below WPF GUI how to convert to Linq due to low performance:
foreach (Grid b in main_grid.Children)
{
foreach (Control s in b.Children)
{
if (s.GetType() == typeof(Button))
{
if (s.Tag.ToString() == message)
{
if (status == "OIRS_INUSE")
{
s.Background = Brushes.Orange;
}
else
{
s.Background = defaultBackground;
}
}
}
}
}
First, you are asking the wrong question. Linq doesn't help.
One way to speed up this loop is to reduce the workload of its bottleneck:
foreach (Grid b in main_grid.Children)
{
foreach (Control s in b.Children)
{
if (s.SomeEnumValue == SomeEnum.Value)
{
s.Background = Brushes.Orange;
}
else
{
s.Background = defaultBackground;
}
}
}
First comparison if (s.GetType() == typeof(Button)) is costly:
for 100 million calls:
typeof(Test): 2756ms
TestType (field): 1175ms
test.GetType(): 3734ms
you'll have more than 5 times slower than a simple field comparison.
Second comparison if (s.Tag.ToString() == message) and third comparison status == "OIRS_INUSE" are costly
Moreover, the second comparison contains a ToString method which has its own cost.
So get rid of all these expensive comparisons and replace them with a simple field comparison such as an enum which is cheap.

How do I turn .Any into a for loop? [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 8 years ago.
Improve this question
I'm having some trouble turning the following code into a for loop. The purpose of the code is to check if the string has both a letter and a number in it.
else if (!string.Any(Char.IsLetter) || !string.Any(Char.IsDigit))
{
return false;
}
Any ideas?
Do you mean something like this?
bool anyLetter = false;
bool anyDigit = false;
foreach(var ch in str)
{
if(char.IsLetter(ch)) anyLetter = true;
if(char.IsDigit(ch)) anyDigit = true;
if(anyLetter && anyDigit) break;
}
return anyLetter || anyDigit;
Note that if this string should contain at least one digit and one letter, you need to use && instead of ||
Since Selman22 seems to have already answered the question, another solution I found is I guess you could also use RegEx:
letterCount = Regex.Matches(yourstring,#"[a-zA-Z]").Count;
numberCount = Regex.Matches(yourstring,#"\d").Count;
return letterCount != 0 && numberCount != 0;
Did you mean a loop for a set of strings?
var src = new List<string>{"A4C", "D3F", "G7I"};
var allHaveCharAndDigit = src.TrueForAll(s => s.Any(c => char.IsLetter(c)) && s.Any(c => char.IsDigit(c)));

How to allow average to be null [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 8 years ago.
Improve this question
how do i allow this get to be null?
public double? GetSignalAverage
{
get
{
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}
SignalStrength is an Int
Check if the collection is null or empty:
public double? GetSignalAverage
{
get
{
if(Gsmdata == null || GsmData.Count() == 0)
return null;
var signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
return Math.Round(signalaverage, 2);
}
}
You'll have to declare SignalStrength as int? to allow null values. (If you don't, int will be its default value, which is 0.) But even then, Average() will simply ignore those values, if there is any non-null element (see the documentation).
If they all are null, Average will return null, which you can catch and return, like this:
double? signalaverage = Gsmdata.Select(x => x.SignalStrength)
.Average();
if(signalaverage == null)
{
return signalaverage; // which is essentially 'return null;'
}
else
{
return Math.Round(signalaverage, 2);
}

How can I handle the situation opposite to my condition? [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 9 years ago.
Improve this question
I have a foreach loop where the code doesn't need to run in one special case. I've done it like this:
if (!IsZoom && entry.StartDate.Year != Year && entry.EndDate.Year != Year)
{
}
else
{
// my code...
}
Somehow I am not happy with that. Is it maybe better to write this as follows?
bool foo = !IsZoom && entry.StartDate.Year != Year && entry.EndDate.Year != Year;
if (!foo)
{
// my code...
}
Reverse your logic. Invert all your boolean expressions, and replace AND with OR:
if (IsZoom || entry.StartDate.Year == Year || entry.EndDate.Year == Year) {
// Do something...
}

Categories

Resources