lambda question

  • Thread starter Thread starter Peter Larsen [CPH]
  • Start date Start date
P

Peter Larsen [CPH]

Hi,

I have a question related to lambda expresions and how to prevent exceptions in a FindAll().
The following code create a list of objects and search for an item the "old" way and the "new" way:

Create the list.
List<object> list2 = new List<object>() { 1, 2, null, 6 };

Search for item "6" the old way.
List<object> temp4 = list2.FindAll(delegate(object obj)
{
if (null != obj)
{
return object.Equals(obj.ToString(), "6");
}
else
{
return false;
}
});

Search for item "6" the new way.
List<object> temp3 = list2.FindAll(obj => object.Equals(obj.ToString(), "6"));


The first method goes just fine because i'm able to check for null items.
The second method fails because of the null item.

How do i check for null items in the second method ??

Thank you in advance.

BR
Peter
 
Peter Larsen said:
I have a question related to lambda expresions and how to prevent exceptions in a FindAll().
The following code create a list of objects and search for an item the "old" way and the "new" way:

Create the list.
List<object> list2 = new List<object>() { 1, 2, null, 6 };

Search for item "6" the old way.
List<object> temp4 = list2.FindAll(delegate(object obj)
{
if (null != obj)
{
return object.Equals(obj.ToString(), "6");
}
else
{
return false;
}
});

Search for item "6" the new way.
List<object> temp3 = list2.FindAll(obj => object.Equals(obj.ToString(), "6"));


The first method goes just fine because i'm able to check for null items.
The second method fails because of the null item.

How do i check for null items in the second method ??

The same way as before. Just because it's a lambda expression doesn't
mean you can't use a block:

List<object> temp4 = list2.FindAll(obj =>
{
if (null != obj)
{
return object.Equals(obj.ToString(), "6");
}
else
{
return false;
}
});

Personally though, I'd go with:

List<object> temp4 = list2.FindAll(obj => object.Equals(obj, 6));
 
Thanks Jon,

I just use object to simplify the sample code.
I you replace the object with your own class, you would still have the proble, right ??

/Peter
 
Peter Larsen said:
I just use object to simplify the sample code.
I you replace the object with your own class, you would still have the proble, right ??

If you use object.Equals, that will take care of nullity for you for
the actual comparison. The problem in your example is that you're
trying to call a method on the null reference before you even call
Equals.
 
Back
Top