且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查我的数组中是否有重复的值?

更新时间:2022-11-01 12:48:42

你可以用一点 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;
    }
}