-3

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
heyNow
  • 866
  • 2
  • 19
  • 42
  • 1
    What do you have? Do you have an array, a list, an `IEnumerable`, or what? What is inside of that collection? What are you trying to do with that collection? Show some sample input/output. – Servy Oct 14 '13 at 21:18

2 Answers2

3

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0
bool nameExists = pList.Any(p=>p.Name == "testName");

or (if you won't use Any ):

bool nameExists = pList.Select(p=>p.Name).Contains("testName");
Marek Woźniak
  • 1,766
  • 16
  • 34