如果C#中的语句有更简单的方法吗?

3 c#

我有以下内容:

if (model.PartitionKey.Substring(2, 2) == "05" || 
    model.PartitionKey.Substring(2, 2) == "06")
Run Code Online (Sandbox Code Playgroud)

我更喜欢这个.是否有更简洁的方法来编码,我不必重复model.PartitionKey两次?

Dar*_*mas 11

那这个呢:

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

这让你可以自由地保留你正在寻找的字符串......

var lookingFor = new string[]{"05", "06"};
var substring = model.PartitionKey.Substring(2, 2);
if (lookingFor.Contains(substring))
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

如果您要查找的字符串列表长度超过两个,这将有很大帮助......此外,您可以将其添加到set(HashSet<string>)以获得更高效的查找 - 但首先要测试它,因为开销可能会增加收益.


Nik*_*wal 9

对于这种情况,我使用扩展方法

public static bool In<T>(this T source, params T[] list)
{
   if (source = null)
       throw new NullReferenceException("Source is Null");

   return list.Contains(source);
}
Run Code Online (Sandbox Code Playgroud)

并称之为

if (model.PartitionKey.Substring(2, 2).In("05", "06"))
Run Code Online (Sandbox Code Playgroud)

作为一种扩展方法,我们可以为所有类型调用它

if(myintegervariable.In(3, 4));
Run Code Online (Sandbox Code Playgroud)

要么

if(mybytevariable.In(23, 56, 34, 43, 87, 155));
Run Code Online (Sandbox Code Playgroud)


Sur*_*ler 7

var keyString = model.PartitionKey.Substring(2, 2);
if (keyString == "05" || keyString == "06")
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • OP只是想避免重复model.PartitionKey两次.这样做一次只保存结果而不是优化? (3认同)
  • @Joey:`temp`从来都不是很好的命名.考虑一下这个变量可能会在一个巨大的方法中使用.关键是,`modelPkYear`会更加安全无虞. (2认同)

jes*_*cah 5

我很惊讶没人提供开关作为可能的选择:)

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

您可以在MSDN上阅读更多相关信息