gpt4 book ai didi

c# - 从列表中选择数据并显示在listBox中,C#

转载 作者:行者123 更新时间:2023-11-30 23:32:01 25 4
gpt4 key购买 nike

所以,我为员工制作了这个类(class),现在我需要从列表中选择,例如所有 25 岁或以上的开发人员,让我们说,也按姓名对他们进行排序,以显示在我创建的列表框中.到目前为止没有成功,我明白我必须使用Linq,并写一些类似的东西

private void button1_Click(object sender, EventArgs e)
{
var query = Employee.Where(Employee => employee.Age > 25);
}

但它给了我 Where 错误,它无法识别语法。另外,我不知道如何选择其他数据。

public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
public string Company { get; set; }
public string Position { get; set; }

public override string ToString()
{
return string.Format("{0} {1}", Name, Age);
}
}

public class Program
{
public static void Main()
{
List<Employee> personList = new List<Employee>()
{
new Employee(){ Name="Steve", Age =23, Position="Developer"},
new Employee(){ Name="Mark", Age =32, Position="Designer"},
new Employee(){ Name="Bill", Age =23, Position="Developer"},
new Employee(){ Name="Nill", Age =25, Position="Analyst"},
new Employee(){ Name="Kevin", Age =28, Position="Analyst"},
new Employee(){ Name="Steve", Age =22, Position="Designer"}
};
}
}

最佳答案

好吧,如果您想选择集合中的特定字段,您应该这样写:

personList
.Where(x => x.Age > 25) //This is where your conditions should be
.OrderBy(x => x.Name) //That's how you order your collection
.Select(x => new //And that's the part where you select your fields
{
Text = x.Name,
Age = x.Age
});

基本上,通过这种选择,您可以创建匿名对象。

但要填充选择列表,您不应创建匿名对象,而应创建特定的枚举,您也可以使用 linQ 来完成:

personList
.Where(x => x.Age > 25)
.Select(x => new ListItem //note that here you create ListItem
{
Text = x.Name,
Value = x.Age
});

关于c# - 从列表中选择数据并显示在listBox中,C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34437426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com