Question

I have a class

class Person {

 int Age;
 string Name;
}

List<Person> pList = new List<Person>();

 pList.Exists(p=> p.Name == "testName");  <-- need an alternative for this.

I'm using .net 3.0.

As such I don't have access to getFirstOrDefault method.

The Exists method throws an exception for null values, but I don't want to interrupt my program flow; is there any other alternative?

I don't have Any or Linq available either.

Was it helpful?

Solution

Exists should be fine - you just need to handle the possibility of p being null.

bool nameExists = pList.Exists(p => p != null && p.Name == "testName");

Alternatively, make sure that your list doesn't contain any null references to start with - that may well make all kinds of things easier for you.

OTHER TIPS

bool nameExists = pList.Any(p=>p.Name == "testName");

or (if you won't use Any ):

bool nameExists = pList.Select(p=>p.Name).Contains("testName");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top