检查日期是否低于2010年?

时间:2013-01-18 15:50:32

标签: c#

我正在尝试向2010年之前聘用的Grid员工展示。我该怎么做?我有一个具有属性(FirstName,LastName,Id和EmploymentDate)的类Employee

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

6 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

试试这个:

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

答案 2 :(得分:2)

如何改变这个:

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

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

最终可能不需要.ToList()部分,但我添加它以与您的实际数据结构保持一致。我建议首先尝试不使用.ToList(),看看是否有效。

答案 3 :(得分:2)

您可以使用Linq过滤它:

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

当然最好不要首先添加它们来检查DateTime.Year属性。

答案 4 :(得分:0)

尝试:

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

您可能需要添加

        using System.Linq;

答案 5 :(得分:0)

var query = from e in _employees
            where e.EmploymentDay.Year < 2010
            select e;