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

  • Thread starter Thread starter Andrew Robinson
  • Start date Start date
A

Andrew Robinson

Any easy answer what is wrong here?

private List<string> BodyWords = new List<string>();

string word = "Andrew";



the following causes a compilation error:



if (!BodyWords.Exists(word))

{

}

Thanks,
 
Alright, looks like I should be using 'Contains' instead of 'Exists' but I
would still like to understand the difference and what a Predicate is?

Thanks,
 
Andrew Robinson said:
Any easy answer what is wrong here?

private List<string> BodyWords = new List<string>();
string word = "Andrew";

the following causes a compilation error:

if (!BodyWords.Exists(word))

{

}

Well, the easy answer is because the List<T>.Exists method doesn't take
a T, it takes a Predicate<T>. I suspect you actually want
List<T>.Contains instead.
 
Hi Andrew,
your problem is that the Exists method expects a Predicate<T> which is
another way of saying you need to put a delegate that returns a bool and
accepts a type of T i.e. delegate bool Predicate<T>(T obj)

So if you want to search your list to see if it contains a value of "Andrew"
you will need to create a method that matches the delegate signature (i.e.
one that returns a bool and accepts the type you define your list as being
(in your case string)

i.e.
private bool ContainsAndrew(string val)
{
return val == "Andrew";
}

//now to your list you would say:

List<string> BodyWords = new List<string>();
BodyWords.Add("Peter");
BodyWords.Add("Paul");

bool containsAndrew = BodyWords.Exists(ContainsAndrew);

The list will then iterate through all the items in the list, calling the
ContainsAndrew method against each item until a match is found (if there is a
match).

Hope that helps
Mark Dawson
http://www.markdawson.org
 
Andrew Robinson said:
Alright, looks like I should be using 'Contains' instead of 'Exists' but I
would still like to understand the difference and what a Predicate is?

A Predicate is something which returns true or false when given an item
of the appropriate type. For instance, here's a Predicate<string> which
tests for a string having a length 5 or more:

Predicate<string> lengthTester = delegate(string x)
{ return x.Length >= 5; };

(That's using an anonymous method, but a Predicate<T> is just like any
other delegate.)
 
Alright, looks like I should be using 'Contains' instead of 'Exists' but I
would still like to understand the difference and what a Predicate is?

Predicate is simply a generic delegate with the signature

delegate bool Predicate<T> (T val)

and you're supposed to supply such an instance to Exists. It will
return true if the predicate returns true for any item. So you can do
something like

if (!BodyWords.Exists(delegate (string s) { return s == word; }))


Mattias
 
Back
Top