Reputation: 25
So, I have made this class for the employees, now I need to select from the list, for example all developers aged 25 or older and let's say, order them by name also, to show up in my listBox that I created. Didn't succeeded so far, I understand that I must use Linq, and write something like
private void button1_Click(object sender, EventArgs e)
{
var query = Employee.Where(Employee => employee.Age > 25);
}
But it gives me error for Where, it doesn't recognize the syntax. Also, I can't figure out how to select the other data.
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"}
};
}
}
Upvotes: 2
Views: 794
Reputation: 12491
Well if you want to select particular fields of your collection you should write like this:
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
});
Basically with this kind of select you creating anonymous object.
But to fill select list you should create not anonymous object but particular enumeration and you also can do it with linQ:
personList
.Where(x => x.Age > 25)
.Select(x => new ListItem //note that here you create ListItem
{
Text = x.Name,
Value = x.Age
});
Upvotes: 2