Dheeman Dutta

Just Another Blog.....

  Home  |   Contact  |   Syndication    |   Login
  39 Posts | 1 Stories | 29 Comments | 12 Trackbacks

News



Archives

Post Categories

.NET Links

All what I had to do was to check whether , my List<> object contains any object with a SelectedDate (a property of the object) having a certain value. And I did not want to loop in the List and find out . (tomorrow there may be 10000 items in my list , and a loop would be very very slow). I found that a List exposes a property called Exits() which can do the trick for me .....

static void Main(string[] args)

{

List<Dinosour> _DinoList = new List<Dinosour>();

Dinosour d1 = new Dinosour();

d1.Name="TREX";

d1.Gender="M";

_DinoList.Add(d1);

Dinosour d2 = new Dinosour();

d2.Name = "Bronto";

d2.Gender = "F";

_DinoList.Add(d2);

Dinosour d3 = new Dinosour();

d3.Name = "Raptor";

d3.Gender = "F";

 

_DinoList.Add(d3);

bool c= _DinoList.Exists(CheckIfExists);

Console.WriteLine("Dino :" + c);

Console.ReadKey();

}

 

//****************************

private static bool CheckIfExists(Dinosour d)

{

if (d.Name == "TREX")

return true;

else

return false;

}

//************************

public class Dinosour

{

private string myVar;

public string Name

{

get { return myVar; }

set { myVar = value; }

}

private string _Gender;

public string Gender

{

get { return _Gender; }

set { _Gender = value; }

}

}

 

However One disadvantage , i found was that the value to be checked needs to be more or less predetermined as the delegate method does not take any other parameters. Any suggestions would be appreciated.....

 

Cheers...

posted on Wednesday, October 25, 2006 8:39 AM

Feedback

# re: Check whether a List contains any object having a certain property value.... 11/14/2006 4:47 AM Suman
Thanks man that was what I was looking for exactly

# re: Check whether a List contains any object having a certain property value.... 5/21/2009 8:15 AM Bogdan Wojcieszyk
Regarding your comments at the end of the article - you have to use closures. Roughly, your code would look like this


public static Predicate<Dinosour> ElementWithThisIdExists(int id)
{
return delegate(Dinosour dino)
{
if (dino.Id == id)
{
return true;
}
else
{
return false;
}
};
}

Then you check for existance of a given value:
bool b = _dinoList.Exists(ElementWithThisIdExists(5));


# re: Check whether a List contains any object having a certain property value.... 7/29/2009 3:14 AM rory
Excellent solution with the delegate (Bogdan post) - proper .net!

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: