Is there a simpler way to do this if statement in

2020-04-10 23:04发布

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 ?

标签: c#
7条回答
Animai°情兽
2楼-- · 2020-04-10 23:08

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

the syntax might be far off, corrections are welcome :)

Edit: new []

查看更多
可以哭但决不认输i
3楼-- · 2020-04-10 23:17

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));
查看更多
ら.Afraid
4楼-- · 2020-04-10 23:20
var keyString = model.PartitionKey.Substring(2, 2);
if (keyString == "05" || keyString == "06")
{
    // ...
}
查看更多
smile是对你的礼貌
5楼-- · 2020-04-10 23:21

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.

查看更多
够拽才男人
6楼-- · 2020-04-10 23:24

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.

查看更多
劳资没心,怎么记你
7楼-- · 2020-04-10 23:28

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

查看更多
登录 后发表回答