c# - 如何在类属性中找到值?
问题描述
我有一长串 100 名学生的名单。我正在构建一个按学生姓名搜索学生的“查找”对话框。这是我的类属性:
我的代码
public partial class FF : Window
{
public FF()
{
InitializeComponent();
List<User> items = new List<User>();
items.Add(new User() { Name = "John Doe", Age = 42 });
items.Add(new User() { Name = "Jane Doe", Age = 39 });
items.Add(new User() { Name = "Sammy Doe", Age = 13 });
lvStudents.ItemsSource = items;
}
public class User
{
public string Name { get; set; }
public int Age { get; set; }
}
我的 XAML
<DockPanel Grid.Row="0" Grid.Column="10" Grid.ColumnSpan="10" Grid.RowSpan="10">
<ListView Name="lvStudents">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" Width="100" DisplayMemberBinding="{Binding Name}" />
<GridViewColumn Header="Age" Width="30" DisplayMemberBinding="{Binding Age}" />
</GridView>
</ListView.View>
</ListView>
</DockPanel>
**我尝试过的事情**
private void FindStudent(string name)
{
if (stud.Name.Any(str => str.Contains(name)))
{
MessageBox.Show("Student found!");
}
else
{
MessageBox.Show("Student not found!");
}
}
每次我运行上面的代码时,我都没有得到任何特定的错误。但是我得到了错误的结果,即找不到学生。为什么?
解决方案
最后,我解决了这个问题。感谢所有贡献并回答我的人。
private void FindStudent(string name)
{
User std = items.FirstOrDefault(s => s.Name.Contains(name));
if (std != null)
{
this.Title = "Student found!";
}
else
{
this.Title = "Student NOT found!";
}
}
推荐阅读
- ios - 如何在 var 名称中使用 #。JSON,iOS,斯威夫特
- asp.net-mvc - 如何在 VS2017 上将 ASP.MVC 脚手架从 Bootstrap 3 更新到 Bootstrap 4?
- c# - 当 web 应用和 apis 服务器分别部署时,授权端点是什么?
- events - 自定义事件调度程序 - JavaFX
- laravel - 从 Postman 或 Guzzle 调用时,Laravel 会话未保存
- go - 如何在 Go 中将 DB 连接初始化作为一个包分开?
- html - 表单发布在 url 中添加数据
- unity3d - 将 .unity 场景文件转换为 YAML,无需接触预制件
- linux - 在 mac OS 中移植 Linux 程序时出现 dlib 错误
- r - R heatmap.2:如何调整颜色键上直方图的 ylim?