Cannot convert from 'int' to 'System.Predicate<int>'

Viewed 86

How to fix this? Or, why is this error showing up. What am I doing wrong. I understand that there is some issue with the datatype but why and what can I do to resolve this?

My C# code:

int[] nums = new int[5];

int i = 0;
while (i < 5)
{
    int num = Convert.ToInt32(Console.ReadLine());
    if (Array.Find(nums, num) != 0)
    {
        Console.WriteLine("Error: Number already inputed. Try a different number.");
        continue;
    }
    i++;
}```

Error:
*Severity   Code    Description Project File    Line    Suppression State
Error   CS1503  Argument 2: cannot convert from 'int' to 'System.Predicate<int>'    udemy lectures beginner section6 exercise   D:\C# practice\C# practice codes\exercises\udemy lectures beginner section6 exercise\udemy lectures beginner section6 exercise\Program.cs   104 Active*  (line 8)
2 Answers

you can create predicate using a lambda syntax

var index = Array.Find (nums, n=> n == num); // n == num returns a bool

//array returns a position of a found item in array if item is found. If it is not found returns -1;

if ( index >= 0 )   // if found
{

// or shorter
if ( Array.Find (nums, n => n == num) >= 0 )   // if found
{
...

but it is usually used of array of complicated objects. For example if array items were not int, but a class with Id and Name properties you could use it

var index=Array.Find (nums, n=> n.Id == num);

For a simple array like yours, it's better to use

if (Array.IndexOf(nums, num) != -1) // index of found item or -1 if not found
{
...

So, I assume that you want to check for duplicates in your array. You only want to add unique inputs to your array,so every number is supposed to be only once in the array, right? Then, the thing you are doing wrong, is that you are trying to overload an int to Array.Find. I guess you want to check if the int is contained within the array. But the type you actually have to use is a predicate. A predicate is nothing more than a Func - a function delegate returning a bool. The proper way to use the find function is to write it as follows.

Array.Find(nums,x => x== num);

Your code should noe look like this.

int[] nums = new int[5];

int i = 0;
while (i < 5)
{
int num = Convert.ToInt32(Console.ReadLine());
if (Array.Find(nums, num) != 0)
{
    Console.WriteLine("Error: Number already inputed. Try a different 
number.");
    continue;
}
i++;
}

But, by using find you are passing a function. This is not the most performant way to solve this problem and you are, as @UnHolySheep already pointed out, probably better up by just checking Indexof(num) != -1.

Related