Skip to main content
 首页 » 编程设计

c#之C# 有集合比较运算符吗

2024年01月13日33www_RR

我有以下 while 语句:

while ((leftSide.Count-rightSide.Count!=-1)&&(leftSide.Count-rightSide.Count!= 0)) 
{ 
     // Do stuff here 
} 

我很想这样写:

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

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

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

我想我可以这样做:

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

但我宁愿不要。

如果没有办法进行“集合”比较,有人知道为什么吗? C# 是一种功能齐全的语言,缺少这样的东西似乎很奇怪。

请您参考如下方法:

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

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

用法:

Int32 i = 10; 
i.In(10, 20, 30); // True