2017-09-14 36 views
0

我在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; 
+1

的可能的複製(https://stackoverflow.com/questions/ 1175645/find-an-item-in-list-by-linq) – mjwills

回答

9

很容易與LINQ:

if(personList.Any(p=> p.Name == "Test")) 
{ 
    // you have to search that person again if you want to access it 
} 

List<T>.Find你必須檢查null

Person p = personList.Find(x => x.Name == "Test"); 
if(p != null) 
{ 
    // access the person safely 
} 

但是如果你需要,你也可以使用LINQ Person

Person p = personList.FirstOrDefault(x => x.Name == "Test"); 
if(p != null) 
{ 
    // access the person safely 
} 

順便說一句,還有一個List<T>方法就像Enumerable.AnyList<T>.Exists:?查找LINQ在列表中的項目]

if(personList.Exists(p=> p.Name == "Test")) 
{ 
    // you have to search that person again if you want to access it 
} 
+0

沒問題。我不知道LINQ是什麼,所以我會開始閱讀一些關於它的東西。 LINQ「更好」然後用列表搜索? – Luranis

+2

@Luranis:只有少數列表方法,但可以使用更多的LINQ方法。另外,雖然列表方法很好,但是如果您想從列表中更改爲「HashSet '或」Person []「,該怎麼辦?你必須改變你的所有代碼,也許在其他集合類中沒有類似的方法。 LINQ適用於任何'IEnumerable ',所以你不會被卡住'List '。 –

+0

因此,如果我總是可以使用LINQ,那麼它最好使用它? – Luranis

相關問題