如何通过linq获取此数据

时间:2015-02-02 22:59:35

标签: c# linq

public class Employee
{
    public int ID { get; set; }
    public string Name { get; set; }
}

public class LoginAudit
{
    public int ID { get; set; }
    public DateTime LoginTime { get; set; }
}



static void Main(string[] args)
{

    List<Employee> AllEmployees = new List<Employee>() 
    {
        new Employee() { ID = 1, Name = "John"},
        new Employee() { ID = 2, Name = "Pete"},
        new Employee() { ID = 3, Name = "Sue"},
        new Employee() { ID = 4, Name = "Chris"},
        new Employee() { ID = 5, Name = "Kate"},
        new Employee() { ID = 6, Name = "Smith"},
        new Employee() { ID = 7, Name = "Bil"},
        new Employee() { ID = 8, Name = "Shan"},
        new Employee() { ID = 9, Name = "Joe"},
        new Employee() { ID = 10, Name = "Lure"}
    };


    List<int> SomeEmployeesIDs = new List<int>() 
    {
        1, 2, 5, 6, 10
    };

    List<LoginAudit> EmployeeLogins = new List<LoginAudit>() 
    {
        new LoginAudit() { ID = 1, LoginTime = new DateTime(2015,1,11)},
        new LoginAudit() { ID = 5, LoginTime = new DateTime(2015,2,2)}
    };

}

我想从符合以下条件的 AllEmployees 员工中选择一切 1.在 SomeEmployeesIDs AND 中拥有ID 2.要么全部登录(意味着 EmployeeLogins 中没有条目),要么他们最后一次登录超过7天)

基于此,我应该得到ID为1,5,6和10的员工。有人可以帮我写Linq查询来检索这些数据吗?

3 个答案:

答案 0 :(得分:2)

我认为你需要这样的东西:

var result = AllEmployees.Where( x=> SomeEmployeesIDs.Contains(x.ID) &&                     
                                ((!EmployeeLogins.Any(y=>y.ID==x.ID) ||
                                   EmployeeLogins.Any(y=> y.ID==x.ID && 
                                   (y.LoginTime-DateTime.Now).Days>7)));

答案 1 :(得分:2)

您可以使用此查询:

var q = from emp in AllEmployees
        join eId in SomeEmployeesIDs on emp.ID equals eId
        where !EmployeeLogins
            .Any(el => el.ID == emp.ID && (DateTime.Now - el.LoginTime).Days <= 7)
        select emp;

Any中的这种情况涵盖了这两种情况,而Join只有an efficient way才能只接受ID在其他集合中的员工。

如果你不喜欢查询语法,你可以使用它(如果集合很小,请使用Contains):

var q = AllEmployees
   .Where(emp => SomeEmployeesIDs.Contains(emp.ID)
          && !EmployeeLogins
            .Any(el => el.ID == emp.ID 
                 && (DateTime.Now - el.LoginTime).Days <= 7));

答案 2 :(得分:2)

使用如下查询:

var employees = AllEmployees.Where(
    e => SomeEmployeesIDs.Contains(e.ID) &&
    (EmployeeLogins.All(l => l.ID != e.ID) || 
    EmployeeLogins.Where(l => l.ID == e.ID).Any(l => (DateTime.Now - l.LoginTime).Days > 7)));