LINQ connection right and left

My task is to refactor some t-sql queries in LINQ. Simple join and left outer join are self explanatory. Here is my code:

string[] leftouter = new string[] { "a", "b", "c", "d", "e" };
string[] inner     = new string[] { "a", "b" };

var q = from s1 in leftouter
        join s2 in inner on s1 equals s2 into j
        from sj in j.DefaultIfEmpty() 
        select string.Format("Outer: {0} Left: {1}", s1, sj)

      

Output:

Outer: a Left: a  
Outer: b Left: b  
Outer: c Left:   
Outer: d Left:   
Outer: e Left:   

      

This is a simple left join. Now I would like to add a new dataset:

string[] rightouter = new string[] { "c", "d", "e" };  

      

Desired result:

Outer: a Left: a Right:  
Outer: b Left: b Right:  
Outer: c Left:   Right: c
Outer: d Left:   Right: d
Outer: e Left:   Right: e

      

How can I reformat LINQ to address this issue? Thanks to

+3


source to share


1 answer


Try the following:



string[] all = {"a", "b", "c", "d", "e"};
string[] left = {"a", "b"};
string[] right = {"c", "d", "e"};

var q = from innerItem in all
        join leftItem in left on innerItem equals leftItem into leftItems
        join rightItem in right on innerItem equals rightItem into rightItems
        from a in leftItems.DefaultIfEmpty()
        from b in rightItems.DefaultIfEmpty()
        select string.Format("Outer: {0} Left: {1} Right: {2}", innerItem, a, b);

      

+7


source







All Articles