C# nicer way of writing if statement with two values [closed] - c#

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";

Related

Is there more efficient way to use !=? [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 3 years ago.
Improve this question
Sometimes i need to use != two, three or four times is there a better way to do it?
if (result != 1 && result != 12)
{
do something
}
if (result != 1 && != 12)
{
do something
}
second option would be better, nut we all know it doesn't work
There is not a direct way in the language like the one you suggested:
// Wont compile
if (result != 1 && != 12) { }
If you only have a few values to check, I'd use the explicit comparsions. However you can create a collection of values an check if the result is not in the colleciton:
// using System.Linq;
if (!(new []{ 1, 2 /*, ... */ }).Contains(result)) { }
As suggested in the comments you can also write an extension method. This requires a public static class:
public static class ExtensionMethods
{
public static bool NotIn(this int num, params int[] numbers)
{
return !numbers.Contains(num);
}
}
// usage
result.NotIn(1, 12);
result.NotIn(1, 12, 3, 5, 6);
And if you want to compare not only integers, you can write a generic method:
public static bool NotIn<T>(this T element, params T[] collection)
{
return !collection.Contains(element);
}
// Works with different types
result.NotIn(1, 2, 3, 4);
"a".NotIn("b", "c", "aa");
You can use Linq All() method probably
if((new int[]{1,12,13}).All(x => x != result))
{
// do something
}

Optimize if -else statement Ask [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
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.

How to Pass Next Level Alphabetical String using C#? [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 6 years ago.
Improve this question
I would like to pass if input string is "A" means i need to get next leve as "B". If input value is "B" means "C".
E.g:
string input1 = "A";
string input2 = "B";
output:
input1 ---> B
input2 ---> C
How to do it in programmatically. Please give me a solution to do this.
This is the best as far as i understand the problem:
public char NextLevel(char c)
{
if (c == 'Z')
return 'A';
return (char)(c + 1);
}
private string NextChar(string character)
{
if (character == null) throw new ArgumentNullException(nameof(character));
if (character.Length != 1) throw new ArgumentOutOfRangeException(nameof(character), "You can use only a single letter string");
return Convert.ToString(NextChar(character[0]));
}
private char NextChar(char character)
{
return (char)(character + 1);
}
If you need more details you can use this link: https://github.com/jenseralmeida/stackoverflow/blob/q37608162/src/LibraryTests/DraftTests.cs
This should work for you.
public string NextAlphaString(string x)
{
if(x == "z" || x == "Z")
return x.Replace(x[0],(char)(x[0] - 25));
else
return x.Replace(x()[0],(char)(x[0] + 1));
}

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 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