Thursday, October 16, 2008

List.Exists(Predicate match)

Hi,

At times when you want to check for an Item inside a List list, you can use the Exists method as follows.

List.Exists(Predicate match)

List l = new List();
l.Add("Red");
l.Add("Green");
l.Add("Blue");
l.Add("Purple");

//prints "true" as "Red" is in the list
Console.WriteLine(l.Exists(delegate(string s) { return s == "Red"; }));

//prnts "false" as "Pink" is not in the list
Console.WriteLine(l.Exists(delegate(string s) { return s == "Pink"; }));
Published 30 September 04 08:00 by BradA
http://blogs.msdn.com/brada/archive/2004/09/30/236460.aspx

In my case I had to check against an object and not the string.

this will work, SourceFieldID is of type string.
bool itemExists = _criteriaItems.Items.Exists(delegate(CriteriaItem ci) { return ci.SourceFieldId == item.SourceFieldId; });

but this wont work, it will always return false.
bool itemExists = _criteriaItems.Items.Exists(delegate(CriteriaItem ci) { return ci == item; });

happy coding!!

3 comments:

Imran said...

Hi Palkar,

in C# 3.0, you just need to write single line without delegate, this uses the lmbda expression.

Console.Write(l.Exists(p => p.Equals("Red")));

Have fun with C# 3.0.

We Three said...

Palkar,

Some more features of C# 3.0

* Extention method
public static int Squre(this int n)
{
return n*n ;
}


The method will added in Squre method for integer type veriable

int i = 2;
int j = i.Squre(); //j=4

* Object Initializers

short hand object initializer methods

public class Point
{
public int x ;
public int y;
}

We can declare and initialize a Point object using an object initializer, like this:

Point point = new Point{ x = 0, y= 0} ;

this is same as
Point point = new Point();
point.x =0;
point.y=0;

Deepak said...

That's great.
Well I'm glad I added this blog here, trying to shade some light on things that I learned and in rewards I learned things even better ;)

thanks guys!!