How to do joins in LINQ on multiple fields in single join

前端 未结 13 1924
小鲜肉
小鲜肉 2020-11-22 17:02

I need to do a LINQ2DataSet query that does a join on more than one field (as

var result = from x in entity
join y in entity2 
       on x.field1 = y.field1          


        
相关标签:
13条回答
  • 2020-11-22 17:45
    from d in db.CourseDispatches
                                 join du in db.DispatchUsers on d.id equals du.dispatch_id
                                 join u in db.Users on du.user_id equals u.id
                                 join fr in db.Forumreports on (d.course_id + '_' + du.user_id)  equals  (fr.course_id + '_'+ fr.uid)
    

    this works for me

    0 讨论(0)
  • 2020-11-22 17:51

    Just to complete this with an equivalent method chain syntax:

    entity.Join(entity2, x => new {x.Field1, x.Field2},
                         y => new {y.Field1, y.Field2}, (x, y) => x);
    

    While the last argument (x, y) => x is what you select (in the above case we select x).

    0 讨论(0)
  • 2020-11-22 17:54

    Using the join operator you can only perform equijoins. Other types of joins can be constructed using other operators. I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause. Documentation on the join clause can be found here. MSDN has an article on join operations with multiple links to examples of other joins, as well.

    0 讨论(0)
  • 2020-11-22 17:55

    As a full method chain that would look like this:

    lista.SelectMany(a => listb.Where(xi => b.Id == a.Id && b.Total != a.Total),
                    (a, b) => new ResultItem
                    {
                        Id = a.Id,
                        ATotal = a.Total,
                        BTotal = b.Total
                    }).ToList();
    
    0 讨论(0)
  • 2020-11-22 17:56

    If the field name are different in entities

    var result = from x in entity
       join y in entity2 on 
              new {
                    field1=   x.field1,
                   field2 =  x.field2 
                 } 
              equals
             new { 
                    field1= y.field1,
                    field2=  y.myfield
                  }
    select new {x,y});
    
    0 讨论(0)
  • 2020-11-22 17:57
    var result = from x in entity1
                 join y in entity2
                 on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }
    

    You need to do this, if the column names are different in two entities.

    0 讨论(0)
提交回复
热议问题