C# 从列表中选择数据并将其显示在列表框C中
因此,我为员工创建了这个类,现在我需要从列表中选择,例如,所有25岁或以上的开发人员,也可以按姓名排序,以显示在我创建的列表框中。到目前为止还没有成功,我知道我必须使用Linq,并编写类似的内容C# 从列表中选择数据并将其显示在列表框C中,c#,linq,listbox,C#,Linq,Listbox,因此,我为员工创建了这个类,现在我需要从列表中选择,例如,所有25岁或以上的开发人员,也可以按姓名排序,以显示在我创建的列表框中。到目前为止还没有成功,我知道我必须使用Linq,并编写类似的内容 private void button1_Click(object sender, EventArgs e) { var query = Employee.Where(Employee => employee.Age > 25); } 但是它给了我一个错误,它不能识别语法。另外,
private void button1_Click(object sender, EventArgs e)
{
var query = Employee.Where(Employee => employee.Age > 25);
}
但是它给了我一个错误,它不能识别语法。另外,我不知道如何选择其他数据
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
});
我认为lambda表达式中的Employee术语与类名匹配。将其更改为emp,但这不仅仅是一个问题。在您的示例中,我看到了混合应用程序:控制台和桌面Web。对您最好的建议是了解什么是LINQ,在哪里以及如何使用它。首先,在查询中,将雇员更改为雇员,或者反之亦然,以便名称匹配……但这会给我错误的位置,它无法识别语法。另外,我不知道如何选择其他数据。你不认为在使用它之前需要先学习语法吗?您所问的是非常基本的问题。如果您查询的是集合,而不是class.var query=Employee.WhereEmployee=>Employee.Age>25,这也会有所帮助;lambda表达式与类名相同。您可以更改为var query=Employee.Whereemp=>emp.Age>25;要按名称订购,可以添加.OrderByemp=>emp.name