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

后端 未结 7 1437
说谎
说谎 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:40

    For such kind of cases I use an Extension Method

    public static bool In(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));
    

提交回复
热议问题