I have the following:
if (model.PartitionKey.Substring(2, 2) == \"05\" ||
model.PartitionKey.Substring(2, 2) == \"06\")
I have more like t
if (new []{"05", "06"}.Contains(model.PartitionKey.Substring(2, 2))
the syntax might be far off, corrections are welcome :)
Edit: new []
For such kind of cases I use an Extension Method
public static bool In<T>(this T source, params T[] list)
{
if (source = null)
throw new NullReferenceException("Source is Null");
return list.Contains(source);
}
and call it as
if (model.PartitionKey.Substring(2, 2).In("05", "06"))
Being an Extension Method we can call it for all types like
if(myintegervariable.In(3, 4));
OR
if(mybytevariable.In(23, 56, 34, 43, 87, 155));
I'm surprised nobody offered switch as a possible alternative :)
switch (model.PartitionKey.SubString(2,2)) {
case "05":
case "06":
// do stuff
break;
// other cases
default:
// like an else
}
You can read more about it at MSDN
What about this:
if (new string[]{"05", "06"}.Contains(model.PartitionKey.Substring(2, 2))
// ...
That leaves you at liberty to keep the strings you are looking for in a nice list...
var lookingFor = new string[]{"05", "06"};
var substring = model.PartitionKey.Substring(2, 2);
if (lookingFor.Contains(substring))
{
// ...
}
This will help a lot if the list of strings you are looking for gets longer than just two... Also, you can then add this to a set (HashSet<string>
) for more efficient lookup - but test this first, as overhead can eat up gains.
You can save the substring in a variable:
var substring = model.PartitionKey.Substring(2, 2);
if (substring == "05" || substring == "06")
Or you could use a regular expression:
if (Regex.IsMatch("^..0[56]", model.PartitionKey))
This probably depends a bit on how easily you can understand a regex while reading code.
var keyString = model.PartitionKey.Substring(2, 2);
if (keyString == "05" || keyString == "06")
{
// ...
}