Help Understanding Enumerable.Join Method

前端 未结 4 685
时光取名叫无心
时光取名叫无心 2021-02-04 11:45

Yesterday I posted this question regarding using lambdas inside of a Join() method to check if 2 conditions exist across 2 entities. I received an answer on the question, which

4条回答
  •  死守一世寂寞
    2021-02-04 12:03

    Eric and Nick have both provided good answers.

    You may also write the Linq query expression using query syntax (vs. method syntax, which you are using in your example):

    var query = from a in db.TableA 
                join b in db.TableB on a.someFieldID equals b.someFieldID
                where a.UserID == currentUser && b.MyField == someValue
                select a;
    
            if (query.Any()) {
                ...
            }
    

    Update:

    You seem to be stuck on the lambda expressions. It's a function that you pass around like a variable. A lambda expression is equivalent to an anonymous delegate (or anonymous method, to me more general).

    Here is your query with the lambda expressions as delegates (replace EntityType with the type of your entity returned from TableA, of course):

    if (db.TableA.Where( delegate(EntityType a) { return a.UserID == currentUser; } ) 
      .Join( db.TableB.Where( delegate(EntityType b) { return b.MyField == someValue; } ), 
             delegate(EntityType o) { return o.somefieldId); },
             delegate(EntityType i) { return i.someFieldId); },
             delegate(EntityType o, EntityType i) { return o; }) 
      .Any())  
    

    { //... }

    NOTE: A lambda expression has important aspects that make it more than just an equivalent for anonymous methods. I recommend that you look through other SO questions and read online about lambda expressions in particular. They allow for very powerful ideas to be expressed in a much simpler and elegant way. It's a deep topic, but the basics are easy enough to understand. It's a function that you can pass around like a variable, or as a parameter to other functions.

提交回复
热议问题