首页 > 解决方案 > 如何在类属性中找到值?

问题描述

我有一长串 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!");
        }
    }

每次我运行上面的代码时,我都没有得到任何特定的错误。但是我得到了错误的结果,即找不到学生。为什么?

标签: c#wpf

解决方案


最后,我解决了这个问题。感谢所有贡献并回答我的人。

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!";
    }
}

推荐阅读