Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

c# - How do I check if my array has repeated values inside it?

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...