【问题标题】:Select data from the list and display it in the listBox, C#从列表中选择数据并显示在listBox中,C#
【发布时间】:2016-03-29 23:48:00
【问题描述】:

所以,我为员工创建了这个类,现在我需要从列表中进行选择,例如所有 25 岁或以上的开发人员,假设也按名称排序,以显示在我创建的列表框中.到目前为止没有成功,我知道我必须使用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"}
        };
    }
}

【问题讨论】:

  • 我认为 lambda 表达式中的 Employee 术语与类名匹配。将其更改为 emp,但这不仅仅是一个问题。在您的示例中,我看到混合应用程序:控制台和桌面(Web)。对您来说最好的建议是了解什么是 LINQ 以及 在哪里 以及 如何 可以使用它
  • 对于初学者,在查询中将 Employee 更改为 employee 或反之亦然,以便名称匹配...
  • "但是它给了我 Where 的错误,它无法识别语法。另外,我不知道如何选择其他数据。"你不认为在使用它之前你需要先学习语法吗?你问的是非常基本的。
  • 查询集合而不是类也会有所帮助。
  • var query = Employee.Where(Employee =&gt; employee.Age &gt; 25); lambda 表达式与类名相同。您可以更改为var query = Employee.Where(emp =&gt; emp.Age &gt; 25);按名称订购您可以添加.OrderBy(emp =&gt; emp.Name)

标签: c# linq listbox


【解决方案1】:

如果你想选择你收藏的特定字段,你应该这样写:

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

【讨论】:

    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-04
    • 2012-11-15
    • 2016-04-21
    相关资源
    最近更新 更多