-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.

4

2 回答 2

3

Exists应该没问题 - 你只需要处理存在的p可能性null

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

或者,确保您的列表不包含任何null开头的引用 - 这可能会使您的各种事情变得更容易。

于 2013-10-14T21:30:41.320 回答
0
bool nameExists = pList.Any(p=>p.Name == "testName");

或(如果您不使用Any):

bool nameExists = pList.Select(p=>p.Name).Contains("testName");
于 2014-10-01T14:52:19.437 回答