[英]How do I find a value inside class properties?
I have a long list of 100 students.我有一长串 100 名学生的名单。 I am building a Find dialog that searches for students by their name.我正在构建一个按学生姓名搜索学生的“查找”对话框。 Here are my class properties:这是我的 class 属性:
My code我的代码
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; }
}
My XAML我的 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>
** Things I tried** **我尝试过的事情**
private void FindStudent(string name)
{
if (stud.Name.Any(str => str.Contains(name)))
{
MessageBox.Show("Student found!");
}
else
{
MessageBox.Show("Student not found!");
}
}
Every time I run the above code, I don't get any specific error.每次我运行上面的代码时,我都没有得到任何特定的错误。 But I get wrong result that the student was not found.但是我得到了错误的结果,即找不到学生。 Why?为什么?
private void connectDb()
{
SqlConnection conn = new SqlConnection("YOUR DATABASE LOCATION/ DATABASE PATH");
conn.Open(); // initalize your database connection
}
private void searchForStudentName()
{
string name;// = your textbox that holds value of students name;
this.connectDb(); //your connection into database
SqlCommand cmd = new SqlCommand("Select * from ['YOUR TABLE NAME'] where Name = @Name",conn);
cmd.parameters.AddWithValue("@Name", name);
dr= cmd.ExcecuteReader();
if(dr.Read())//meaning, the system found the value of the input data/ name
{
ListViewItem lvi = new ListViewItem(dr["NAME"].ToString);// name will be displayed in listview control
listView1.items.add(lvi);
}else
{
//there is no data found
}
}
Finally, I fixed the issue.最后,我解决了这个问题。 Thanks to all those who contributed and answered me.感谢所有贡献并回答我的人。
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!";
}
}
Do做
if (stud.Any(st => st.Name.Contains(name)))
instead of代替
if (stud.Name.Any(str => str.Contains(name)))
With "using System.Linq;"与“使用 System.Linq;” of course当然
PS "stud" as we can see in the question, is List. PS“螺柱”正如我们在问题中看到的那样,是列表。 We call Any() method on the list of students, and pass a lambda-predicate which checks name of every student.我们在学生列表上调用 Any() 方法,并传递一个 lambda 谓词来检查每个学生的姓名。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.