Is there a simpler way to do this if statement in C#

后端 未结 7 1522
说谎
说谎 2021-01-21 03:05

I have the following:

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

I have more like t

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-21 03:47

    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) for more efficient lookup - but test this first, as overhead can eat up gains.

提交回复
热议问题