我有一個Customer對象的列表,我試圖在每個對象中搜索一個名稱。在Customer對象中有一個屬性ContactData,它返回一個Contact對象。而在Contact對象中,我有一個方法返回一個名字的字符串。正是我試圖與之比較的名稱,但它不能正常工作,因爲我每次都會受到攻擊,儘管我搜索的是任何Customer對象中不存在的名稱。我正在使用的代碼:在對象列表中搜索
foreach (Customer name in m_customers)
{
if (name.ContactData.FullName == "Anna")
{
MessageBox.Show(string.Format("Yes"), "Test!", MessageBoxButtons.OK, MessageBoxIcon.Information); // Just for testing
}
}
我也測試過使用簡單for循環,但是我得到了相同的結果。我不確定我做了正確的事情,並會提供一些幫助!謝謝!
在foreach循環中插入一個簡單的'console.writeline'調用,以便爲循環中的每個項目打印ContactData.FullName。你的變量命名很混亂,你可能想'foreach(客戶客戶在m_customers中)' – ChristopheD
你是否驗證了'm_customers'包含了一個唯一對象列表? – ChrisF
你能解釋一下,ChrisF? –