Define String

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I want to define a string value in a short way, if possible, as
follows:

Weight = "Light" if Count < 10, "Normal" if Count >= 10 and < 20,
"Heavy" if Count >= 20

How can I do this?

Thanks,
Miguel
 
shapper said:
I want to define a string value in a short way, if possible, as
follows:

Weight = "Light" if Count < 10, "Normal" if Count >= 10 and < 20,
"Heavy" if Count >= 20

How can I do this?

weight = count < 10 ? "Light" : (count < 20 ? "Normal" : "Heavy");

Personally I wouldn't do that - it's confusing to read. I'd use
if/else:

string weight;
if (count < 10)
{
weight = "Light";
}
else if (count < 20)
{
weight = "Normal";
}
else
{
weight = "Heavy";
}

More space, but easier to read. You could use a conditional for the
normal/heavy but if/else to differentiate between light and
(normal/heavy) though.
 
weight = count < 10 ? "Light" : (count < 20 ? "Normal" : "Heavy");

Personally I wouldn't do that - it's confusing to read. I'd use
if/else:

string weight;
if (count < 10)
{
    weight = "Light";}

else if (count < 20)
{
    weight = "Normal";}

else
{
    weight = "Heavy";

}

More space, but easier to read. You could use a conditional for the
normal/heavy but if/else to differentiate between light and
(normal/heavy) though.

--
Jon Skeet - <[email protected]>
Web site:http://www.pobox.com/~skeet 
Blog:http://www.msmvps.com/jon.skeet
C# in Depth:http://csharpindepth.com

Maybe use a switch/case?
In my example I used only three values but it will have around 8.

This is for a Tag Cloud ... the strings are the CSS Class of each tag
according to its frequency.
I am using ASP.NET MVC, so I am passing the count to my View and
building the CSS Class there ...

Thanks,
Miguel
 
shapper said:
Maybe use a switch/case?
In my example I used only three values but it will have around 8.

No, you can't define ranges in a switch/case.
 
Maybe use a switch/case?
In my example I used only three values but it will have around 8.

The nested if else is very readable, so why not just stick with it.

With 8 ranges you will get more more lines. But what so ? You do not pay
per line of code (I hope) !

If it is <10, <20, ... , <70 then you could switch on count/10. But
the code would not be very flexible.

Arne
 
Back
Top