简体   繁体   English

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

[英]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.

相关问题 按基本路径过滤路径列表的最有效/优雅的方法是什么? - What is the most efficient/elegant way to filter a path list by a base path? 询问MethodInfo需要多少参数的最有效方法是什么? - What is the most efficient way to ask a MethodInfo how many parameters it takes? 重载构造函数/方法的最优雅的方法是什么? - What is the most elegant way to overload a constructor/method? 什么是实现GetTextAfterMarker()的最优雅的方法 - What is the most elegant way to implement GetTextAfterMarker() 在c#中并行异步加载多个变量的最优雅方法是什么? - What is the most elegant way to load multiple variables asynchronously in parallel in c# 确定字符串长度是否最有效的方法!= 0? - Most efficient way to determine if a string length != 0? 确定字符串中第一个字符的最有效方法? - Most efficient way to determine first character in string? 计算IEnumerable集合的并集的最优雅,最有效的方法 - The most elegant and efficient way of calculate union of a collection of IEnumerable 使副本中的副本唯一的最有效方法 - Most efficient way to make duplicates unique in collection 在EF 4.1中进行与LINQ的许多关系进行比较的最有效方法是什么? - What is the most efficient way to do comparisons involving many-many relationships with LINQ in EF 4.1?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM