简体   繁体   English

在多个值上使用布尔运算符的快捷方式

[英]Shortcut to use boolean operators on multiple values

First off, sorry if the title isn't clear or descriptive; 首先,如果标题不清晰或描述性,请对不起; I didn't know what to write exactly. 我不知道该写些什么。

I'm wondering if there is a better way to do this operation: 我想知道是否有更好的方法来执行此操作:

bool result = variable1.innerValue.level2.innerValue == 1 || 
              variable1.innerValue.level2.innerValue == 2 || 
              variable1.innerValue.level2.innerValue == 3;

We can't write something like: 我们写不出类似的东西:

bool result = variable1.innerValue.level2.innerValue == (1 || 2 || 3);

This will give a syntax error. 这将产生语法错误。

Any ideas? 有任何想法吗?

You could use a collection as placeholder and Enumerable.Contains : 您可以使用集合作为占位符和Enumerable.Contains

if(new[]{1, 2, 3}.Contains(variable1.innerValue.level2.innerValue))
{

}

or, for what it's worth, this extension: 或者,为了它的价值,这个扩展:

public static bool In<T>(this T source, params T[] list)
{
  if(null==source) throw new ArgumentNullException("source");
  return list.Contains(source);
}

which enables you to write this: 这使你能够写下这个:

if(variable1.innerValue.level2.innerValue.In(1, 2, 3))
{

}

What are your favorite extension methods for C#? 你最喜欢的C#扩展方法是什么? (codeplex.com/extensionoverflow) (codeplex.com/extensionoverflow)

In this case. 在这种情况下。 you can do Enumerable.Range(1, 3).Contains(variable1.innerValue.level2.innerValue) . 你可以做Enumerable.Range(1, 3).Contains(variable1.innerValue.level2.innerValue)

using System.Linq;
...
bool result = new[] {1, 2, 3}.Contains(variable1.innerValue.level2.innerValue);
var listToCheck = new int[]{1,2,3};
var innerValue = variable1.innerValue.level2.innerValue;

bool result = listToCheck.Contains(innerValue);

Honestly, the first thing that comes to my mind is the good old Introduce Explaining Variable refactoring, which not only reduces the duplication but also makes your code more self-explanatory: 老实说,我想到的第一件事是好的旧介绍解释变量重构,这不仅减少了重复,而且使你的代码更加不言自明:

var innerValue = variable1.innerValue.level2.innerValue;
bool result = innerValue == 1 || innerValue == 2 || innerValue == 3;

怎么样

(new List<int>(){1,2,3}).Exists(i=>i == variable1.innerValue.level2.innerValue)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM