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

时间:2015-12-23 14:06:22

标签: c# linq listbox

所以,我已经为员工制作了这个课程,现在我需要从列表中选择,例如所有25岁或以上的开发人员,让我们说,按名称命名,以便显示在我的我创建的listBox。到目前为止还没有成功,我明白我必须使用Linq,并编写类似

的内容
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"}
        };
    }
}

1 个答案:

答案 0 :(得分:2)

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

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
   });