patterncsharpMinor
Condensing if statement in C#
Viewed 0 times
condensingstatementstackoverflow
Problem
I have this if statement
As you can see it's pretty long and nasty. Is there a way to shrink it? I was going to use a switch but in C# you can't fall through case statements.
if (dt.Month > 3 && dt.Month = 0 && hours = 8 && hours = 12 && hours = 16 && hours = 0 && hours = 8 && hours = 13 && hours = 17 && hours <= 20)
{
session = String.Empty;
}
else if (hours == 21)
{
session = String.Empty;
}
else
{
session = String.Empty; // I dont think this one is needed
}
}As you can see it's pretty long and nasty. Is there a way to shrink it? I was going to use a switch but in C# you can't fall through case statements.
Solution
Shouldn't you replace the whole code with
Let's assumme that this is just a placeholder for actual code. If you handle your different cases in order and if
becomes
session = String.Empty; ?Let's assumme that this is just a placeholder for actual code. If you handle your different cases in order and if
hours is an int, then you can make the logic a bit easier to follow :if (hours == 23 || (hours >= 0 && hours = 8 && hours = 12 && hours = 16 && hours <= 20)
{
session = E;
}
else if (hours == 22)
{
session = F;
}
else
{
session = G;
}becomes
if (hours 23)
{
session = G;
}
else if (hours <=6)
{
session = A;
}
else if (hours <= 7)
{
session = B;
}
else if (hours <= 11)
{
session = C;
}
else if (hours <= 15)
{
session = D;
}
else if (hours <= 20)
{
session = E;
}
else if (hours <= 22)
{
session = F;
}
else
{
session = A;
}Code Snippets
if (hours == 23 || (hours >= 0 && hours <= 6))
{
session = A;
}
else if (hours == 7)
{
session = B;
}
else if (hours >= 8 && hours <= 11)
{
session = C;
}
else if (hours >= 12 && hours <= 15)
{
session = D;
}
else if (hours >= 16 && hours <= 20)
{
session = E;
}
else if (hours == 22)
{
session = F;
}
else
{
session = G;
}if (hours < 0 || hours > 23)
{
session = G;
}
else if (hours <=6)
{
session = A;
}
else if (hours <= 7)
{
session = B;
}
else if (hours <= 11)
{
session = C;
}
else if (hours <= 15)
{
session = D;
}
else if (hours <= 20)
{
session = E;
}
else if (hours <= 22)
{
session = F;
}
else
{
session = A;
}Context
StackExchange Code Review Q#31731, answer score: 2
Revisions (0)
No revisions yet.