我在Google上找不到如何解決我的問題。 我也看到了微軟文檔,但由於某種原因,它不會工作。找到列表中的元素<T>並檢查是否等於值
我做了一個班我的名單與一些Propertys
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Count { get; set; }
}
然後我創建了我的名單在我的主類。
List<Person> personList = new List<Person>();
現在我們來解決我的問題。我想檢查是否存在具有Name屬性=「Test」的項目。如果是,我想顯示一個返回結果的MessageBox。 我試圖
if(personList.Find(x => x.Name == "Test"))
不要工作。
if(personList.Find(x => x.Name.Contains("Test"))
不工作。
Person result = personList.Find(x => x.Name == "Test");
if(result.Name == "Test")
不工作。
我得到的消息就像我不能將Person轉換爲字符串/布爾值。 如果我嘗試結果我得到的消息,該對象未設置爲對象實例。 我不明白這個錯誤,因爲我在我的主類的開始創建了一個實例。 另外我認爲我需要一個空檢查。因爲我想在項目在列表中之前檢查項目是否存在。這是一個事件。我的想法全碼:
TreeViewItem treeViewItem = sender as TreeViewItem;
DockPanel dockpanel = treeViewItem.Header as DockPanel;
List<TextBlock> textblock = dockpanel.Children.OfType<TextBlock>().ToList();
TextBlock name = textblock[0];
TextBlock age = textblock[1];
Person test = personList.Find(x => x.Name == name.Text);
if(test.Name == name.Text)
{
MessageBox.Show(test.Name);
test.Count++;
}
personList.Add(new Person { Name = name.Text, Count = 1, Age = age.Text });
CollectionViewSource itemCollectionViewSource;
itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource"));
itemCollectionViewSource.Source = personList;
的可能的複製(https://stackoverflow.com/questions/ 1175645/find-an-item-in-list-by-linq) – mjwills