[英]What is the most elegant/efficient way to determine if many variables are unique?
If I have five variables 如果我有五个变量
int a,b,c,d,e;
What is the most efficient way to make sure they are all unique? 确保它们都是唯一的最有效方法是什么?
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??
}
Elegant 优雅
int[] arr = { a, b, c, d, e };
bool b = arr.Distinct().Count() == arr.Length;
Efficient 高效的
Your code is the most efficient
I guess that is the most simple explanation of your question. 我想这是对您问题最简单的解释。
That pretty much is the most efficient way. 那几乎是最有效的方法。 It's not necessarily the best looking code I've seen but it'll work just fine.
它不一定是我见过的最好看的代码,但可以正常工作。 Any other solution involving data structures or functions is unlikely to be faster.
任何其他涉及数据结构或功能的解决方案都不可能更快。
I'd recode it for beauty though: 我将其重新编码为美观:
if (a != b && a != c && a != d && a != e
&& b != c && b != d && b != e
&& c != d && c != e
&& d != e
) {
// Blah blah blah
}
Not necessarily exactly like that, just something a bit easier on the eyes when reading. 不一定完全一样,只是一些阅读时对眼睛更容易一些。
I would think something like: 我会想这样的:
int[] x = new int[] {a,b,c,d,e};
if (x == x.Distinct().ToArray())
{
}
If we're playing code golf we can knock this all down to one line and shave 6 characters: 如果我们在打代码高尔夫,我们可以将所有代码都打成一行,然后剃掉6个字符:
bool d = (new int[]{ a, b, c, d, e })
.GroupBy(i => i)
.Where(i => i.Count() > 1)
.Any();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.