Mario Mario - 5 days ago 5
C# Question

How to check array duplicated value

I don't know how to check array, if value already exist



My code should check two values of array . If Two or more values are the same, but instead is checking element positions of array.

int[] polje = new int[10];
for (int i = 0; i < polje.Length; i = i + 1)
{
polje[i] = int.Parse(Console.ReadLine());
*if(polje[i] == i)* //*Check if two or more values are duplicated or the same!*
{
Console.WriteLine("You have entered two or more");
}
}

Answer

You could just use distinct

int[] polje = new [] {3,5,7,8,15};
bool twoOrMoreSame = polje.Distinct().Count() != polje.Length; //false

int[] polje2 = new[] { 3, 5, 7, 3, 8, 15 };
bool twoOrMoreSame2 = polje2.Distinct().Count() != polje2.Length; //true
Comments