2013-10-14 34 views
-3

我有一個類C#:替代品存在或getfirstordefault

class Person { 

int Age; 
string Name; 
} 

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

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

我使用.NET 3.0。

因此,我無法訪問getFirstOrDefault方法。

Exists方法拋出空值的異常,但我不想中斷我的程序流程;有沒有其他的選擇?

我沒有AnyLinq可用。

+1

你有什麼?你有一個數組,一個列表,一個'IEnumerable',或者什麼?那個集合裏面有什麼?你想用這個系列做什麼?顯示一些示例輸入/輸出。 – Servy

回答

3

Exists應該沒問題 - 您只需要處理pnull的可能性。

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

另外,請確保您的列表中不包含任何null引用入手 - 這可能使各種事情變得更容易。

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

或者(如果你不會使用Any):

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