Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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)
like image 693
Anshuman Avatar asked Oct 23 '25 17:10

Anshuman


1 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
{
...
like image 105
Serge Avatar answered Oct 26 '25 08:10

Serge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!