tags:

views:

1017

answers:

2

I have the following expression

        var q = from c in D1 
                join dp in
                    (from e in E1
                     group e by e.ID into g
                     select new { ID = g.Key, Cnt = g.Count() })
                on c.ID
                equals dp.ID 
                into dpp from v in dpp.DefaultIfEmpty() 
                select new { c.ID, Cnt= v.Cnt ?? 0 };

How can i convert this to Lambda expression?

+1  A: 

Why would you want to convert it?

For complex queries like this one the query syntax you have used here is invariably clearer.

Garry Shutler
I don't agree. GroupJoin is clearer as an extension method call, than in a query comprehension blob.
David B
A: 

Here's one way to go. This kind-of matches the above.

var subquery = E1
  .GroupBy(e => e.Id)
  .Select(g => new { ID = g.Key, Cnt = g.Count()});
  //.ToList();

var q = D1
  .GroupJoin(
    subquery,
    c => c.ID,
    dp => dp.ID,
    (c, g) => new {ID = c.ID, Cnt=g.Any() ? g.First().Cnt : 0 }
  )

After refactoring, I came up with this:

var q = D1
  .GroupJoin(
    E1,
    d => d.ID,
    e => e.ID,
    (d, g) => new {ID = d.ID, Cnt = g.Count()}
  );

For comparision, the query comprehension form is:

var q = from d in D1
  join e in E1 on d.ID equals e.ID into g
  select new {ID = d.ID, Cnt = g.Count()};
David B
Is Groupjoin an equivalent to subquery? Please explain this point..thanks
Your subquery had a group by, then the "join .. into" (which is a group join) was regrouping. One does not need to group twice in order to produce the correct answer : Ids from D1 and a count of matches from E1.
David B
http://msdn.microsoft.com/en-us/library/bb534297.aspx"GroupJoin produces hierarchical results, which means that elements from outer are paired with collections of matching elements from inner. GroupJoin enables you to base your results on a whole set of matches for each element of outer."
David B
hanks for link..Ok so you mean a subquery was not needed there? Can you tell me in what example would a subquery be needed then assuming two tables are order and order details
In SQL, one might use subqueries instead of joins to avoid cartesian duplication of results. ORDER JOIN DETAILS yields Order1 several times. This can lead to double counting, etc. Since Linq can work with heirarchies instead of flat results, this need is much reduced.
David B
Subquerying in LINQ is simply applying query method calls to different collections within the query. Here's an example of subquerying in the select "clause":CntOdd = g.Where(e => e.ID % 2 == 1).Count()
David B
Thanks for your prompt answeres..So the sample I posted would not be an example of a subquery in LINQ right..since I do not need a subquery there right? What do I call it then..is GroupJoin a correct name to categorize this kind of a query?