【问题标题】:How do I compare multiple values against a single variable? [duplicate]如何将多个值与单个变量进行比较? [复制]
【发布时间】:2020-05-19 08:49:07
【问题描述】:

是否有比较多个值的快捷方式,例如以下表达式?

if (choice == "a" || choice == "b" || choice == "c") {do something;}

我考虑过 switch 语句,但据我所知,它们仅适用于单个值。

那么变量声明或常量呢?

int initialValue = 1, finalValue = 1;

【问题讨论】:

  • 这是否回答了您的问题:stackoverflow.com/questions/12911691/…?
  • @IliarTurdushev 如果这些值不是数字怎么办?
  • 可以在switch case 中使用任何常量值。
  • @IliarTurdushev 而且,当他们有一系列值时,他们必须像这样写age > 9 && age < 15,而不是简单地写9 < age < 15,在我看来,它更具可读性。跨度>
  • @JohnathanBarclay 一系列值呢?一个一个地写它们可能不是一个好习惯。我可以将这个age > 9 && age < 15 重写为类似9 < age < 15 的东西吗?在我看来,它更具可读性。

标签: c# if-statement switch-statement


【解决方案1】:

你可以试试Any()

public static string[] array = new string[] {"a", "b", "c"};
if(array.Any(x => x == choice))
{
   //Your business logic
}

或者你可以试试Any().Contains

if(array.Any(choice.Contains))
{
   //Your business logic
}

您可以使用HashSet<T> 来存储不同的元素,并使用.Contains() 来确定@​​987654333@ 是否在 hashet 中可用

public static HashSet<string> array = new HashSet<string>(){"a", "b", "c"};
if(array.Contains(choice))
{
   Console.WriteLine("Implement your business logic");
}

.Net Fiddle

【讨论】:

  • Contains() 会更简洁。
  • 考虑HashSetContains
  • @DavidMcNeil,如果您想扩展此 if 条件,请考虑未来,然后在您的方法中您需要添加一个或多个条件,但在我的解决方案中,我们只需要向静态数组添加一条记录
【解决方案2】:

您可以堆叠 case 语句,以便将多个值映射到同一个操作:

switch(choice)
{
  case "a":
  case "b":
  case "c":
    // Do something
    break;

  default:
    // Do something else
    break;
}

【讨论】:

  • 我猜,这适用于这种情况,但是数字范围或更多值呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-07
  • 1970-01-01
  • 1970-01-01
  • 2011-07-19
相关资源
最近更新 更多