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

后端 未结 7 1434
说谎
说谎 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:38

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

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

    Edit: new []

    0 讨论(0)
  • 2021-01-21 03:40

    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));
    
    0 讨论(0)
  • 2021-01-21 03:46

    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

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

    0 讨论(0)
  • 2021-01-21 03:56

    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.

    0 讨论(0)
  • 2021-01-21 03:57
    var keyString = model.PartitionKey.Substring(2, 2);
    if (keyString == "05" || keyString == "06")
    {
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题