<newbie> generic list problem

J

Jeff

..NET 2.0

I'm having trouble with using a Exists method in generic lists. So here I
shows an example list and hope maybe some of you could give me some tips on
how to implement that Exists method

List<string> cars = new List<string>();
cars.Add("BMW");
cars.Add("Volvo");
cars.Add("Toyota");
cars.Add("Hyundai");

Now lets say I should test if an element in the list exists with the value
"Toyota".:

if (cars.Exists())
{
}
Here it stops for me, I'm not sure what to send in as parameters to the
Exists method. I've read the doc about the Exists method, it says it need a
Predicate as a parameter.. how do i create an predicate for this simple
list?

any suggestions are most welcome

Jeff
 
A

Alex Meleta

Hi Jeff,

You can write this, of course:
cars.Exists(delegate(string s) { return "Toyota".Equals(s); })

But it's better to use cars.Contains("Toyota") in your case. Exists it's
custom Contains, by predicate.

Regards, Alex
[TechBlog] http://devkids.blogspot.com
 
B

Bram

Hey Jeff,

You shouldn't use exists(), but contains():

if(cars.Contains("Toyota")) {
Console.Writeline("Landcruiser baby!");
}

Regards,
Bram
 
C

Clive Dixon

As an anonymous delegate

if (cars.Exists(
delegate(string s)
{
if (s == "Toyota")
{
return true;
}
return false;
}
)
{
}

or else

bool IsToyota(string s)
{

if (s == "Toyota")
{
return true;
}
return false;
}

void SomeMethod()
{
if (cars.Exists(IsToyota))
{
}
}
 
J

Jon Skeet [C# MVP]

As an anonymous delegate

if (cars.Exists(
delegate(string s)
{
if (s == "Toyota")
{
return true;
}
return false;
}
)
{

}

As others have suggested, Contains is the best way forward here.
However, if you *do* want to use an anonymous method, there's a rather
more compact way of representing it:

if (cars.Exists(delegate (string s)
{ return s=="Toyota"; }
))
{
...
}

Of course, you don't even need to break the line really, but I tend to
put anonymous method bodies on their own lines.

C# 3 is even more compact:

if (cars.Exists (s=> s=="Toyota"))

:)

Jon
 
C

Clive Dixon

Fair point about Contains - I'd only just got in and not even had my first
coffee of the day...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top