繁体   English   中英

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

[英]Select data from the list and display it in the listBox, C#

所以,我为员工制作了这个课程,现在我需要从列表中进行选择,例如所有 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
   });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM