More elegant if statement - c#

I'm looking to compare a value against a list and then set another variable based on this comparison.
My list is
1 = Red
4 = Blue
13 = Green
I could have a series of if statements but with a large list this looks messy
if (Type == 1)
{
Name = "Red";
}
else if (Type == 4)
{
Name = "Blue";
}
else if (Type == 13)
{
Name = "Green";
}
What's an efficient and tidy way to achieve the same?

Make use of dictionary store your values, it will make clean code with less line of code and readable too
Dictionary<int, string> data = new Dictionary<int, string>
{
{ 1, "Red" },
{ 4, "Blue" },
{ 13, "Green" }
};
string test;
if (data.TryGetValue(1, out test)) // Returns true.
{
Console.WriteLine(test);
}

I think you need to use switch here:
switch (Type)
{
case 1:
Name = "Red";
break;
case 4:
Name = "Blue";
break;
case 13:
Name = "Green";
break;
}

Use a switch statement insted
switch (Type)
{
case 1:
Name = "Red";
break;
case 4:
Name = "Blue";
break;
case 13:
Name = "Green";
break;
}

class Program
{
public enum EnumDisplayStatus
{
Red = 1,
Blue = 2,
Yellow = 3,
Orange = 4
}
static void Main()
{
int value = 3;
EnumDisplayStatus enumDisplayStatus = (EnumDisplayStatus)value;
string color = enumDisplayStatus.ToString();
Console.Write(color);
}
}
Use enum and get string with this way that I showed.

Related

How to get the month name using Dictionary in C#?

I have implemented the first three letters of the month to full name of the month in get Full Month function it is returned based on three letters .
But how to implemented in Dictionary concept Any one simplify modify this code given below code:
**public static string getFullMonth(string mthname)
{
string Mthname = "";
switch (mthname.ToUpper())
{
case "JAN":
Mthname ="January";
break;
case "FEB":
Mthname = "February";
break;
case "MAR":
Mthname = "March";
break;
case "APR:":
Mthname = "April";
break;
case "MAY":
Mthname = "May";
break;
case "JUN":
Mthname = "June";
break;
case "JUL":
Mthname = "July";
break;
case "AUG":
Mthname = "August";
break;
case "SEP":
Mthname = "September";
break;
case "OCT":
Mthname = "October";
break;
case "NOV":
Mthname = "November";
break;
case "DEC":
Mthname = "December";
break;
default:
Console.WriteLine("Invalid grade");
break;
}
return Mthname;
}**
simplify this code given below code
Yes, don't use a dictionary at all:
public static string GetFullMonth(string englishShortMonthName)
{
CultureInfo englishCulture = CultureInfo.InvariantCulture;
if (DateTime.TryParseExact(englishShortMonthName, "MMM", englishCulture, DateTimeStyles.None, out DateTime dt))
return dt.ToString("MMMM", englishCulture);
return englishShortMonthName;
}
Read about the month ("M", "m") format specifier
Look up Dictionary syntax. Ultimately you're looking for something like this:
var monthNames = new Dictionary<string, string>
{
{ "JAN", "January" },
{ "FEB", "February" },
...
}
Please find complete solution
public static string getFullMonth(string mthname)
{
var monthNames = new Dictionary<string, string>
{
{ "JAN", "January" },
{ "FEB", "February" },
...
}
return monthNames[mthname];
}
But above code looks weird So You should create dictionary globally and initialize in constructor.
Add only below line in getFullMonth function.
return monthNames[mthname];

I want to eliminate all of these case statements (too messy)

I am writing a test program which returns a string "P3-PASS" or "P3-FAIL. In all there are 12 possible tests, P3 to P14 ("P3-FAIL" to "P14-PASS").
I have a button "All_Tests" which calls each test 1 by 1, and the associated button changes colour based on the result.
Ideally I want to do something like PageNum.Background = Brushes.Red, but I can't do this because I can't use a string to access the button. Hence the case statements below. Is there a way to simplify this, because it looks awful. OR is there a way to access the relevant button using a string, or similar. Many Thanks
int PageNum = Int32.Parse(PageTstName);
switch (PageNum)
{
case 3:
if (TstResult == "PASS")
{
Pg3.Background = Brushes.SeaGreen;
Pg3.Foreground = Brushes.White;
}
else // TstResult is "FAIL"
{
Pg3.Background = Brushes.Red;
Pg3.Foreground = Brushes.White;
}
break;
case 4:
if (TstResult == "PASS")
{
Pg4.Background = Brushes.SeaGreen;
Pg4.Foreground = Brushes.White;
}
else // TstResult is "FAIL"
{
Pg4.Background = Brushes.Red;
Pg4.Foreground = Brushes.White;
}
break;
case 5: .....etc
You can create a dictionary that maps the numbers to the controls, e.g.
var controlsByPageNum = new Dictionary<int, Button>()
{
{ 3, Pg3 },
{ 4, Pg4 },
{ 5, Pg5 },
// ...
}
When receiving the test results, you can get the control like this:
int PageNum = Int32.Parse(PageTstName);
var btn = controlsByPageNum[PageNum];
if (TstResult == "PASS")
{
btn.Background = Brushes.SeaGreen;
btn.Foreground = Brushes.White;
}
else // TstResult is "FAIL"
{
btn.Background = Brushes.Red;
btn.Foreground = Brushes.White;
}
Create a method to apply your colors:
private static void ApplyColors(Control control, Brush background, Brush foreground)
{
control.Background = background;
control.Foreground = foreground;
}
And a dictionary to map each case:
private readonly Dictionary<string, Action> dict =
new Dictionary<string, Action>();
Now, in your constructor, fill the dictionary:
dict[$"3~PASS"] = () => ApplyColors(Pg3, Brushes.SeaGreen, Brushes.White);
dict[$"3~FAIL"] = () => ApplyColors(Pg3, Brushes.Red, Brushes.White);
dict[$"4~PASS"] = () => ApplyColors(Pg4, Brushes.SeaGreen, Brushes.White);
dict[$"4~FAIL"] = () => ApplyColors(Pg4, Brushes.Red, Brushes.White);
Here, for each page and result, you define the action to execute. With this, now you can manage your current switch in this way:
var key = $"{PageTstName}~{TstResult}";
if (dict.TryGetValue(key, out Action action))
{
action();
}
else
{
// A non mapped case...
}

How do you execute a method only if another one has been run?

I have a choice for the user in Main using a switch. Depending on what the user chooses, several choices later, the program will either end or not. At least, that is what I'm trying to accomplish.
//This is in Main
string[] menyVal2 = new string[] {"Go to the hotel room", "Go to the dining hall"};
string title2 = "text";
int choice2 = menu(menuChoice2, title2);
switch (choice2)
{
case 0:
hotelRoom();
break;
case 1:
diningHall();
break;
}
Many lines of code later...
public static void save()
{
Console.Clear();
string[] menuChoice = {"Chapter 2", "Back to start"};
string title = "text";
int choice = menu(menuChoice, title);
switch (val)
{
case 0:
if (hotelRoom = true) //this if-statement does not work
{
withoutCross();
}
else if (diningHall = true)
{
withCross();
}
break;
case 1:
Main(new string[] { });
break;
}
}
When I understand your title of the question correctly, then this is a solution:
Make the return type of the method bool and fill it to a variable.
bool isMethodExecuted = MyMethod();
Later you can check with a if-Statement, if the method is executed:
if(isMethodExecuted)
MyOtherMethod();

How can I make loop instead of switch statement?

How can I write this shorter? For each case I have to write this and then It is too long because there are 48 numbers so I need 48 cases. Is there a way to make a loop?
switch (ballBounce.ToString())
{
case "1":
if (ballBounce == n0)
{
textBox1.Text = number.ToString();
}
break;
case "2":
if (ballBounce == n1)
{
textBox1.Text = number.ToString();
}
break;
case "3":
if (ballBounce == n2)
{
textBox1.Text = number.ToString();
}
break; ...
The loop is useless in this case.
You can use dictionary.
private Dictinoary<string, string> cases = new Dictionary<string, string> {
{"1", "one"},
{"2", "two"},
// ...
};
// in some method
string text;
if (cases.TryGetValue(ballBounce.ToString(), out text)){
this.textBox1.Text = text;
}
If you want something smarter than simple value, you can have functions in the dictionary.
private Dictinoary<string, Func<string>> cases = new Dictionary<string, Func<string>> {
{"1", () => "one"},
{"2", () =>
{
if (DateTime.Now.Seconds % 2 == 0) { return "A"; }
else { return "B"; }
}},
// ...
};
// in some method
Func<string> textProvider;
if (cases.TryGetValue(ballBounce.ToString(), out textProvider)){
this.textBox1.Text = textProvider();
}
Based on your ToString()'s, I'm assuming that ballBounce is an int.
if (ballBounce <= 48 && ballBounce > 0)
{
textBox1.Text = ballBounce.ToString();
}
why do you use if with case?
you don't need to check twice.
also if this is the code for every case
textBox1.Text = number.ToString();
then you don't need switch or if
jsut write textBox1.Text = number.ToString(); and you are good to go.
also if you have some cases ony you can do it that way:
switch (ballBounce.ToString())
{
case "1":
case "2":
case"3":
//....
textBox1.Text = number.ToString();
}

Replace 4 different characters

I'm trying to take the user input, E.G. ATCG and replace the letters with TAGC. These are DNA Complementary Bases. For example, if the user was to enter ATCGGGC it would output TAGCCCG. I've managed to replace 1 character, but I'm not sure how to get the others to replace.
namespace DNA_Replication_EASY
{
class Program
{
static string input1;
public static string InputBaseWithSpaces()
{
return string.Join(" ", input1.ToCharArray());
}
public static string OpposingBases()
{
string outputBases1 = input1.Replace("A", "T");
return outputBases1;
}
static void Main(string[] args)
{
Console.WriteLine("Please type out your DNA strand bases E.g. A T C G C A T G");
input1 = Console.ReadLine();
Console.WriteLine(InputBaseWithSpaces());
Console.WriteLine(OpposingBases());
Console.ReadLine();
}
}
}
Use Regex.Replace to replace string based on a dictionary (map):
Dictionary<string, string> complementary = new Dictionary<string,string>()
{
{ "A", "T" },
{ "T", "A" },
{ "C", "G" },
{ "G", "C" }
};
string input = "ATCG";
string result = Regex.Replace(input, "[ATCG]", match => complementary[match.Value]);
this replaces any of the "ATCG" character match with corresponding value from dictionary.
string MakeOpposite(string sourceString) {
var opposites = new Dictionary<char, char> {
{ 'A', 'T' },
{ 'T', 'A' },
{ 'G', 'C' },
{ 'C', 'G' }
};
var oppositeString = new string(sourceString.Select(x => opposites[x]));
return oppositeString;
}
Convert it to a char array and replace in place
string input = "ATCG";
//TAGC
char[] inputChar = input.ToCharArray();
for(int i=0;i< inputChar.Length; i++)
{
switch(inputChar[i])
{
case 'A':
inputChar[i]='T';
break;
case 'T':
inputChar[i]='A';
break;
case 'G':
inputChar[i]='C';
break;
case 'C':
inputChar[i]='G';
break;
}
}
var output =new string(inputChar);
I would use a foreach and switch statement over your Char Array to replace each letter.
foreach (char base in strand)
{
switch (base.ToString())
{
case "g":
//replace code
break;
case "c":
//replace code
break;
}
}
You should instead write a routine to go through character by character and do the replacement (don't use the string.replace method).
private string ConvertDNA(string original)
{
StringBuilder newone = new StringBuilder();
foreach(char c in original)
{
switch(c)
{
case 'A':
newone.Append('T');
break;
case 'T':
newone.Append('A');
break;
case 'C':
newone.Append('G');
break;
case 'G':
newone.Append('C');
break;
default:
newone.Append(c);
break;
}
}
return newone.ToString();
}
Note that if your original string is certain forms of Unicode, this could do funny things. You should use stringbuilder rather than the += syntax in the other answers because its more efficient.
One way to do it is by using a Switch statement
public static string OpposingBases()
{
string outputBases1;
foreach(var s in input1)
{
switch (s)
{
case "A":
outputBases1 +="T";
break;
case "T":
outputBases1 +="A";
break;
case "C":
outputBases1 +="G";
break;
case "G":
outputBases1 +="C";
break;
case " ":
outputBases1 +=" ";
break;
default:
break;
}
}
return outputBases1;
}
Simple solution, but you can do better:
code = code.Replace("A","x").Replace("C","y").Replace("T","A").Replace("G","C").Replace("x","T").Replace("y","G");
You could do this
public static string OpposingBases()
{
var baseDictionary = new Dictionary<char, char>()
{
{'A', 'T'},
{'T', 'A'},
{'C', 'G'},
{'G', 'C'}
};
return input1.Where(baseDictionary.ContainsKey).Aggregate("", (current, c) => current + baseDictionary[c]);
}

Categories