Laura Jimenez
Laura Jimenez

Reputation: 59

How to convert a LINQ query to use lambda expressions

I'm trying to switch this linq code to a lambda expression:

foreach (var id in orderLinesToSplit)
{
    int result =
        (from ol in orderLines
        from splittedOl in orderLines
        where ol.Key == id
            && ol.Value == splittedOl.Value
            && ol.Key != splittedOl.Key
        select splittedOl.Key).FirstOrDefault();
}

The goal is to get a Dictionary<int, int> of pairs id (from oderLinesToSplit) and result (the result from the linq query). Can it be done with just one lambda expression?

Thanks

Upvotes: 1

Views: 539

Answers (1)

Arion
Arion

Reputation: 31239

var result= 
(
    from ol in orderLines
    from splittedOl in orderLines
    where orderLinesToSplit.Contains(ol.Key)
        && ol.Value == splittedOl.Value
        && ol.Key != splittedOl.Key
      select new
      {
        splittedOl.Key,
        splittedOl.Value
      }
    ).ToDictionary (v =>v.Key,v=>v.Value);

Or if you really want it in one expression. Then something like this:

var result=
    (
        db.orderLines.Join
            (
                db.splittedOl,
                ol=>ol.Value,
                splittedOl=>splittedOl.Value,
                (ol,splittedOl)=>new 
                {
                    olKey=ol.Key,
                    splittedOlKey=splittedOl.Key
                }
            ).Where(l =>l.olKey!= l.splittedOlKey && orderLinesToSplit.Contains(l.olKey))
            .ToDictionary(l =>l.olKey,v=>v.splittedOlKey)
    );

Where db is the linq data context

Upvotes: 1

Related Questions