Linq left an external connection to a custom comparator

I am trying to make a left outer join request that also has a custom comparator .

I have the following lists:

 List<ColumnInformation> list1; List<ColumnInformation> list2; 

They contain information about the SQL column (data type, name, table, etc.). I overridden Equals for the class and made operator == and operator != .

I understand how to make a left outer join :

 var leftOuterJoin = from l1 in list1 join l2 in list2 on l1.objectID equals l2.objectID into temp from l2 in temp.DefaultIfEmpty(new { l1.ID, Name = default(string) }) select new { l1.ID, ColumnName1 = l1.Name, ColumnName2 = l2.Name, }; 

And I understand how to create and use a custom IEqualityComparer :

 public class ColumnComparer : IEqualityComparer<ColumnInformation> { public bool Equals(ColumnInformation x, ColumnInformation y) { return x == y; //this uses my defined == operator } public int GetHashCode(ColumnInformation obj) { return 1; //forcing the join to use Equals, just trust me on this } } ColumnComparer cc = new ColumnComparer(); var joinedList = list1.Join(list2, x => x, y => y, (x, y) => new {x, y}, cc); 

My question is: How can I make both a left outer join and use my comparator at the same time ?

As far as I know, the query syntax does not have a keyword for the comparator, and the extension method has nothing for the into keyword.

I don't care if the result is in the query syntax or extension methods.

+4
source share
2 answers

How do you do this with GroupJoin and SelectMany (to smooth out the results):

 ColumnComparer cc = new ColumnComparer(); var joinedList = list1 .GroupJoin(list2, x => x, y => y, (x, g) => new {x, g}, cc) .SelectMany( z => zgDefaultIfEmpty(), (z, b) => new { x = zx, y = b } ); 
+3
source

You can use Sub-Query in combination with Where:

 var leftOuterJoin = from l1 in list1 select new { jointList = (from l2 in list2 where l2.objectID == l1.ObjectID // <-- and you can do any other comparing logic in where clause select l2).DefaultIfEmpty(), l1id = l1.ID, ColumnName1 = l1.Name, ColumnName2 = l2.Name }; 
0
source

Source: https://habr.com/ru/post/1501690/


All Articles