2013-01-18 89 views
-5

我想在2010年之前聘用的Grid員工中展示。我該怎麼做?我有一個類Employee與屬性(名字,姓氏,Id和EmploymentDate)檢查日期是否低於2010?

private List<Employee> _employees = new List<Employee>(); 

private void Form1_Load(object sender, EventArgs e) 
{ 
    Employee employee1 = new Employee(); 

    employee1.FirstName = "Etrit"; 
    employee1.LastName = "Bujupi"; 
    employee1.Id = 1; 
    employee1.EmploymentDay = DateTime.Today; 
    _employees.Add(employee1);    

    Employee employee2 = new Employee(); 

    employee2.FirstName = "Urim"; 
    employee2.LastName = "Sadiu"; 
    employee2.Id = 2; 
    employee2.EmploymentDay = new DateTime(2009, 1, 23); 
    _employees.Add(employee2); 


    Employee employee3 = new Employee(); 

    employee3.FirstName = "Dardan"; 
    employee3.LastName = "Mexhuani"; 
    employee3.Id = 3; 
    employee3.EmploymentDay = new DateTime(2007, 2, 7); 
    _employees.Add(employee3);    

    Employee add = new Employee(); 
    if (_employees < System.DateTime.Now) 
    { 
     EmployeeGrid.DataSource = _employees; 
    } 
} 

回答

2
EmployeeGrid.DataSource = _employees.Where(e => e.EmploymentDay.Year < 2010).ToList(); 
2

試試這個:

EmployeeGrid.DataSource = _employees.Where(x=> x.EmploymentDay.Year < 2010); 
2

如何改變這樣的:

if (_employees < System.DateTime.Now) 
{ 
    EmployeeGrid.DataSource = _employees; 
} 

EmployeeGrid.DataSource = _employees.Where(e => e.EmploymentDay.Year < 2010).ToList(); 

很可能最後的.ToList()部分不需要,但我將其添加爲與您的實際數據結構一致。我建議先嚐試一下沒有.ToList(),看看是否有效。

2

你可以使用Linq對其進行過濾:

employeeGrid.DataSource = _employees.Where(e => e.EmploymentDay.Year < 2010); 

當然,這將是最好不要添加它們首先檢查DateTime.Year財產。

0

嘗試:

 if (_employees < System.DateTime.Now) 
     { 
      EmployeeGrid.DataSource = _employees.Where(s => s.EmploymentDay.Year < 2010); 
     } 

您可能需要添加

 using System.Linq; 
0
var query = from e in _employees 
      where e.EmploymentDay.Year < 2010 
      select e;