convert this LINQ expression into Lambda

后端 未结 7 899
春和景丽
春和景丽 2020-11-29 07:56

Guys, I have a hard time converting this below linq expression(left join implementation) to lambda expression (for learning).

var result = from g in groc         


        
7条回答
  •  我在风中等你
    2020-11-29 08:08

    Here’s how you might write this query in lambda:

    var cus­tomers = new List {
    new Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer1” },
    new Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer2” },
    };
    
    var user­Cus­tomers = new List {
    new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer1”, User = “not-admin” },
    new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer1”, User = “admin” },
    new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer2”, User = “not-admin” },
    new User­Cus­tomer { Com­pa­nyId = “AC”, Cus­tomerId = “Customer2”, User = “admin” },
    new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer1”, User = “not-admin”     },
    new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer1”, User = “admin” },
    new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer2”, User = “not-admin” },
    new User­Cus­tomer { Com­pa­nyId = “not-AC”, Cus­tomerId = “Customer2”, User = “admin” }
    };
    

    Using query expres­sion

    var query =
    from c in cus­tomers
    join uc in user­Cus­tomers on
    new { c.CompanyId, c.CustomerId } equals new { uc.CompanyId, uc.CustomerId }
    where c.CompanyId == “AC” && uc.User == “admin“
    select c;
    

    Using lambda expres­sions

    var lambda =  cus­tomers.Where(c => c.CompanyId == “AC”) // inner sequence
    .Join(userCustomers.Where(uc => uc.User == “admin”), // outer sequence
    c => new { c.CompanyId, c.CustomerId }, // inner key selec­tor
    uc => new { uc.CompanyId, uc.CustomerId }, // outer key selec­tor
    (c, uc) => c);
    

    Both approach yields the same result (cus­tomer with com­pany Id “AC” and cus­tomer Id “Customer1”), but as you can see, lambda expres­sion is much harder to write and read!

    Hope this helps!

提交回复
热议问题