Is there an easier way to do this if the operator in C #

I have the following:

if (model.PartitionKey.Substring(2, 2) == "05" || model.PartitionKey.Substring(2, 2) == "06") 

It seems to me more. Is there a cleaner way to encode this when I don't need to repeat the model. PartitionKey twice?

+3
source share
7 answers

How about this:

 if (new string[]{"05", "06"}.Contains(model.PartitionKey.Substring(2, 2)) // ... 

This leaves you free to keep the lines you are looking for on a good 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 lines you are looking for is longer than two ... Alternatively, you can add this to the set ( HashSet<string> ) for a more efficient search, but check this first, since overhead can eat up the profit .

+11
source

In such cases, I use the 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 name him

 if (model.PartitionKey.Substring(2, 2).In("05", "06")) 

Being an extension method, we can call it for all types, such as

 if(myintegervariable.In(3, 4)); 

OR

 if(mybytevariable.In(23, 56, 34, 43, 87, 155)); 
+9
source
 var keyString = model.PartitionKey.Substring(2, 2); if (keyString == "05" || keyString == "06") { // ... } 
+7
source

I am surprised that no one suggested the switch as a possible alternative :)

 switch (model.PartitionKey.SubString(2,2)) { case "05": case "06": // do stuff break; // other cases default: // like an else } 

Learn more about this on MSDN.

+5
source

You can save the substring in a variable:

 var substring = model.PartitionKey.Substring(2, 2); if (substring == "05" || substring == "06") 

Or you can use regex:

 if (Regex.IsMatch("^..0[56]", model.PartitionKey)) 

This probably depends a bit on how easily you can understand the regex while reading the code.

+3
source

To make reading easier, you can extract the Substring into a variable, and then check that:

 var partitionKeyBits = model.PartitionKey.Substring(2, 2); if (partitionKeyBits == "05" || partitionKeyBits == "06") { } 

But the rest is the case.

+1
source

if (new []{"05", "06"}.Contains(model.PartitionKey.Substring(2, 2))

the syntax may be far away; corrections are welcome :)

Edit: new []

0
source

All Articles