是否为C#设置了比较操作?

Vac*_*ano 1 c# comparison set

我有以下声明:

while ((leftSide.Count-rightSide.Count!=-1)&&(leftSide.Count-rightSide.Count!= 0))
{
     // Do stuff here
}
Run Code Online (Sandbox Code Playgroud)

我想写这样的东西:

while (leftSide.Count - rightSide.Count ! in [-1, 0])
{
     // Do stuff here
}
Run Code Online (Sandbox Code Playgroud)

但这是非法的语法.我想知道,有什么办法吗?一些语法我不知道?

我想看看一组数字中的计数是否有差异,而不必再次重新包括语句的整个左侧?

我想我能做到这一点:

int x = leftSide.Count-rightSide.Count;
while ((x != -1) && (x != 0))
{
     // Do stuff here
     x = leftSide.Count-rightSide.Count;
}
Run Code Online (Sandbox Code Playgroud)

但我宁愿不.

如果没有办法进行"设定"比较,有谁知道为什么?C#是一种功能齐全的语言,这样的东西似乎很奇怪.

dec*_*one 8

使用扩展方法,您可以轻松创建In运算符:

public static class Extensions
{
    public static Boolean In<T>(this T obj, params T[] items)
    {
        return items.Contains(obj);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

Int32 i = 10;
i.In(10, 20, 30); // True
Run Code Online (Sandbox Code Playgroud)


Jon*_*eet 7

它不需要在语言中,因为它可以很容易地在库中:

private static readonly int[] ValidValues = { -1, 0 };

...

if (!ValidValues.Contains(leftSide.Count - rightSide.Count))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

我在这里使用了一个数组,因为它太小......但是你想考虑使用HashSet<int>一个大型集合.