确定许多变量是否唯一的最优雅/最有效的方法是什么

本文关键字:有效 方法 是什么 变量 是否 唯一 许多 | 更新日期: 2023-09-27 18:34:57

如果我有五个变量

int a,b,c,d,e;

确保它们都是独一无二的最有效方法是什么?

if(a!=b && a!=c && a!=d && a!=e && b!=c && b!=d && b!=e && c!=d && c!=e && d!=e)
{ 
   //Is this the most efficient way??
}

确定许多变量是否唯一的最优雅/最有效的方法是什么

优雅

int[] arr = { a, b, c, d, e };
bool b = arr.Distinct().Count() == arr.Length;

有效

Your code is the most efficient

我想这是对你问题最简单的解释。

这几乎最有效的方法。它不一定是我见过的最好看的代码,但它可以正常工作。任何其他涉及数据结构或功能的解决方案都不太可能更快。

不过,我会为了美观而重新编码它:

if (a != b && a != c && a != d && a != e
           && b != c && b != d && b != e
                     && c != d && c != e
                               && d != e
) { 
    // Blah blah blah
}

不一定完全是这样,只是在阅读时

更容易看。

我会这样想:

int[] x = new int[] {a,b,c,d,e};
if (x == x.Distinct().ToArray())
{
}

如果我们在玩代码高尔夫,我们可以将其全部敲成一行并减少 6 个字符:

bool d = (new int[]{ a, b, c, d, e })
              .GroupBy(i => i)
              .Where(i => i.Count() > 1)
              .Any();