Reputation:
I have the following:
if (model.PartitionKey.Substring(2, 2) == "05" ||
model.PartitionKey.Substring(2, 2) == "06")
I have more like this. Is there a more clean way to code this where I don't have to repeat model.PartitionKey twice ?
Upvotes: 3
Views: 346
Reputation: 1528
var keyString = model.PartitionKey.Substring(2, 2);
if (keyString == "05" || keyString == "06")
{
// ...
}
Upvotes: 7
Reputation: 48590
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));
Upvotes: 9
Reputation: 7248
if (new []{"05", "06"}.Contains(model.PartitionKey.Substring(2, 2))
the syntax might be far off, corrections are welcome :)
Edit: new []
Upvotes: 0
Reputation: 975
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
Upvotes: 5
Reputation: 70344
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.
Upvotes: 11
Reputation: 354794
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.
Upvotes: 3
Reputation: 20069
To aid readibility you could extract the Substring
out into a variable and then test that:
var partitionKeyBits = model.PartitionKey.Substring(2, 2);
if (partitionKeyBits == "05" || partitionKeyBits == "06") {
}
But otherwise that is about it.
Upvotes: 1