如何检查我的数组中是否有重复的值? [英] How do I check if my array has repeated values inside it?

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

问题描述

这是我的数组.

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?

我不想使用任何特殊的内置方法,因为这是一个小数组.

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");
}

Distinct 扩展方法删除任何重复项,Count 获取大小结果集的.如果它们完全不同,则列表中有一些重复项.

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 方法将任何相同的元素组合在一起,Any 返回 true 如果任何组有多个元素.

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

上述两种解决方案都通过使用 HashSet,但是你可以像这样直接使用:

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");
}

或者,如果您更喜欢完全不依赖 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天全站免登陆