如何检查我的阵列重复里面的值? [英] How do I check if my array has repeated values inside it?

查看:130
本文介绍了如何检查我的阵列重复里面的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,这里是我的数组。

So here is my array.

double[] testArray = new double[10];
// will generate a random numbers from 1-20, too lazy to write the code

我想打一个搜索循环来检查是否正在重复任意值。我该怎么做呢?

I want to make a search loop to check if any values are being repeated. How do I do that?

我想preFER不使用任何特殊的内置方法,因为这是一小阵。

I would prefer not to use any special built-in methods since this is a small array.

推荐答案

您可以用少许的Linq做到这一点:

You could do this with a little Linq:

if (testArray.Length != testArray.Distinct().Count())
{
    Console.WriteLine("Contains duplicates");
}

鲜明 扩展方法删除任何重复, 计数 得到结果集的大小。如果他们都不同,那么在列表有些重复。

The Distinct extension method removes any duplicates, and Count gets the size of the result set. If they differ at all, then there are some duplicates in the list.

另外,这里的更复杂的查询,但它可能是一个更有效的一点:

Alternatively, here's more complicated query, but it may be a bit more efficient:

if (testArray.GroupBy(x => x).Any(g => g.Count() > 1))
{
    Console.WriteLine("Contains duplicates");
}

GROUPBY 方法将组中的任何相同的元素在一起,的 任何 返回真正如果有任何团体已超过一种元素

The GroupBy method will group any identical elements together, and Any return true if any of the groups has more than one element.

上述两种解决方案通过利用工作的HashSet< T> ,但你可以使用一个直接像这样:

Both of the above solutions work by utilizing a HashSet<T>, but you can use one directly like this:

if (!testArray.All(new HashSet<double>().Add))
{
    Console.WriteLine("Contains duplicates");
}

或者,如果你preFER不依赖于LINQ的根本解决办法:

Or if you prefer a solution that doesn't rely on Linq at all:

var hashSet = new HashSet<double>();
foreach(var x in testArray) 
{
    if (!hashSet.Add(x)) 
    {
        Console.WriteLine("Contains duplicates");
        break;
    }
}

这篇关于如何检查我的阵列重复里面的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆