4

I have to filter Employee based on their department. I'm able to do the same with LINQ.

Linq and lambda compile to get same result. The compiler changes the query expression into the equivalent Lambda expression before compiling it, so the generated IL is exactly the same.Source

var deptCollection = new List<Dept>();
var employeeCollection = new List<Employee>();

employeeCollection.Add(new Employee { Id = 1, Name = "Eldho" });

deptCollection.Add(new Dept { DepetarmentName = "a", EmployeeId = 3 });
deptCollection.Add(new Dept { DepetarmentName = "a", EmployeeId = 1 });

var empinadept = (from e in employeeCollection
                  from dep in deptCollection
                  where e.Id == dep.EmployeeId
                  && dep.DepetarmentName == "a"
                  select e)
                 .ToList();

I can't able to add .Where Clause in this lambda

var empindeptLamda = employeeCollection
                     .Join(deptCollection,
                     emp => emp.Id, dep => dep.EmployeeId,
                     (em, dep) => em.Id == dep.EmployeeId
                      && dep.DepetarmentName == "a")
                     .ToList();

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

class Dept
{
    public int EmployeeId { get; set; }
    public string DepetarmentName { get; set; }
}

Q1. What is the equivalent lambda statement for the above linq ? (How to add where clause as in linq in method-syntax

Cœur
  • 37,241
  • 25
  • 195
  • 267
Eldho
  • 7,795
  • 5
  • 40
  • 77
  • 3
    Use whichever format is more readable... – Austin T French Aug 02 '16 at 12:35
  • 4
    [Is it Linq or Lambda?](http://stackoverflow.com/questions/7391370/is-it-linq-or-lambda) This post is pretty good – Timmy Aug 02 '16 at 12:37
  • 1
    Basically both are Linq, however the one is a query-syntax and the other is the method-syntax. – MakePeaceGreatAgain Aug 02 '16 at 12:38
  • @AustinFrench how should i use where condition with `join` – Eldho Aug 02 '16 at 12:39
  • You add it after the `.Join` or do a join with [multiple conditions](http://stackoverflow.com/questions/7664727/linq-join-with-multiple-conditions-in-on-clause) – Gilad Green Aug 02 '16 at 12:41
  • FYI. The terms are query syntax and method syntax. Both are Linq and lambdas are the anonymous delegate that you tend to use in method syntax. – juharr Aug 02 '16 at 12:50
  • You seem to misunderstand joins and you have written two very confusing queries. The 1st has a double `from`, which translates into a `SelectMany`. But then you filter the results by comparing Id's **which is what join does**, so this query should have been a join. In your 2nd query `(em, dep) => em.Id == dep.EmployeeId && dep.DepetarmentName == "a")` is a **selector**. It **selects** a boolean value. (this query produces an `IEnumerable`, all with the value `true`) The filtering is done by the previous 2 lines. – Dennis_E Aug 02 '16 at 13:19

2 Answers2

9

The equivalent for this:

var empinadept = (from e in employeeCollection
              from dep in deptCollection
              where e.Id == dep.EmployeeId
              && dep.DepetarmentName == "a"
              select e)
             .ToList();

Is this:

var result = employeeCollection.Join(deptCollection,
        e => e.Id,
        dep => dep.EmployeeId,
        (e,dep) => new { e, dep })
    .Where(item => item.dep.DepetarmentName == "a")
    .Select(item => item.e)
    .ToList();

A better option will be to:

var result = employeeCollection.Join(
            deptCollection.Where(dep => dep.DepetarmentName == "a"),
            e => e.Id,
            dep => dep.EmployeeId,
            (e,dep) => e)
       .ToList();

Closest to the query-syntax (but I would say that is less nice opinion based) is:

var result = employeeCollection.Join(
        deptCollection,
        e => new { e.Id, "a" },
        dep => new { dep.EmployeeId, dep.DepartmentName },
        (e,dep) => e).ToList();
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
  • This works for me, when i benchmarked it, Linq is faster than lamda. The figures are 001940 ms for linq and 0058248 for lamda. – Eldho Aug 02 '16 at 13:13
  • @Eldho - I wouldn't rush to say it is faster (might be true but I don't know enough) - I'd check the sql that is being generated and check. Also compare for different Databases – Gilad Green Aug 02 '16 at 13:15
  • This are in memory objects, i have this in a List – Eldho Aug 02 '16 at 13:16
  • ah ok :) also compare what happens when you play with first the Where and then the join and so on, and ToList too, but again could be that you are correct – Gilad Green Aug 02 '16 at 13:17
  • @Eldho - For performance you can start with [this](http://stackoverflow.com/questions/28576999/linq-lambda-vs-query-syntax-performance) – Gilad Green Aug 02 '16 at 13:18
  • Sure, thank you , Do we have any option to write the same with lamda, My project so far only contains lamda no linq, So to stay consistent i should use lamda without lossing performance. i have 2k list to compare with. – Eldho Aug 02 '16 at 13:19
  • 1
    I think using objects like HashSets will be more beneficial for the performance that if it is query or method syntaxs. I'd go with what is more readable - sometimes it is methods, sometimes it is the query - and this is already personal preference too – Gilad Green Aug 02 '16 at 13:21
0

Q1. What is the equivalent lamda statement for the above linq ?

var empindeptLamda = employeeCollection
    .Join(deptCollection, emp => emp.Id, dep => dep.EmployeeId, (e, dep) => new { e, dep })
    .Where(x => x.dep.DepetarmentName == "a")
    .Select(x => x.e)
    .ToList();

Q2. When should i choose LINQ vs Lamda method syntax or query syntax ?

This is really your personal preference. Since they are compiled into the same IL, so the performance is the same. However, there is some situation where query syntax is preferred, such as having multiple join clause. And other time where the method syntax shines, like adding your own extensions method, or debugging the intermediate result between each method.

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44