JOIN by LINQ in C #

0

I need to join LINQ in two lists using codeList. List 1 must exist in the second list (list 2) and needs to be returned. How do I do that? Note: I've never done join via LINQ in C #

    
asked by anonymous 27.07.2016 / 00:48

1 answer

6

You can do this as follows:

OUTER JOIN

var set1 = new HashSet<Entity1>();
var set2 = new HashSet<Entity2>();

var query =
    from entity1 in set1
    join entity2 in set2 on entity1.Codigo equals entity2.Codigo
    select new {
        Entity1 = entity1,
        Entity2 = entity2
    };

LEFT JOIN

var set1 = new HashSet<Entity1>();
var set2 = new HashSet<Entity2>();

var query =
    from entity1 in set1
    join entity2 in set2 on entity1.Codigo equals entity2.Codigo into lSet
    from entity2 in lSet.DefaultIfEmpty()
    select new {
        Entity1 = entity1,
        Entity2 = entity2
    };

Remembering that it is not possible to Right Join , at most you can make a Left Join by reversing the order of the collections.

RIGHT JOIN

var set1 = new HashSet<Entity1>();
var set2 = new HashSet<Entity2>();

var query =
    from entity2 in set2
    join entity1 in set1 on entity2.Codigo equals entity1.Codigo into rSet
    from entity1 in rSet.DefaultIfEmpty()
    select new {
        Entity1 = entity1,
        Entity2 = entity2
    };

It is also not possible to do Full Join in a simple way, you will have to make Left Join and "Right Join" , then join both.

FULL JOIN

var set1 = new HashSet<Entity1>();
var set2 = new HashSet<Entity2>();

var lQuery =
    from entity1 in set1
    join entity2 in set2 on entity1.Codigo equals entity2.Codigo into lSet
    from entity2 in lSet.DefaultIfEmpty()
    select new {
        Entity1 = entity1,
        Entity2 = entity2
    };

var rQuery =
    from entity2 in set2
    join entity1 in set1 on entity2.Codigo equals entity1.Codigo into rSet
    from entity1 in rSet.DefaultIfEmpty()
    select new {
        Entity1 = entity1,
        Entity2 = entity2
    };

var query = lQuery.Union(rQuery);
    
27.07.2016 / 00:55