我在Google上找不到如何解决我的问题.我也看过Microsoft文档但由于某种原因它不会工作.
我用一些Propertys为我的列表制作了一个类
public class Person
{
public string Name { get; set; }
public string Age { get; set; }
public string Count { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后我在我的Main类中创建了List.
List<Person> personList = new List<Person>();
Run Code Online (Sandbox Code Playgroud)
现在我们来解决我的问题.我想检查名称属性="测试"的项目是否存在.如果是,我想显示一个返回结果的MessageBox.我试过了
if(personList.Find(x => x.Name == "Test"))
Run Code Online (Sandbox Code Playgroud)
不要工作.
if(personList.Find(x => x.Name.Contains("Test"))
Run Code Online (Sandbox Code Playgroud)
不要工作.
Person result = personList.Find(x => x.Name == "Test");
if(result.Name == "Test")
Run Code Online (Sandbox Code Playgroud)
不要工作.
我得到的消息就像我无法将Person转换为string/bool.如果我尝试结果,我得到消息,该对象未设置为对象实例.我不明白这个错误,因为我在Main Class的开头创建了一个实例.另外我认为我需要空检查.因为我想在列表中的项目之前检查项目是否存在.这是一个事件.完整的我的想法代码:
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;
Run Code Online (Sandbox Code Playgroud)
LINQ非常简单:
if(personList.Any(p=> p.Name == "Test"))
{
// you have to search that person again if you want to access it
}
Run Code Online (Sandbox Code Playgroud)
与List<T>.Find你必须检查null:
Person p = personList.Find(x => x.Name == "Test");
if(p != null)
{
// access the person safely
}
Run Code Online (Sandbox Code Playgroud)
但是如果你需要,你也可以使用LINQ Person:
Person p = personList.FirstOrDefault(x => x.Name == "Test");
if(p != null)
{
// access the person safely
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,还有一个List<T>是工作方式类似方法Enumerable.Any,List<T>.Exists:
if(personList.Exists(p=> p.Name == "Test"))
{
// you have to search that person again if you want to access it
}
Run Code Online (Sandbox Code Playgroud)