LINQ - Full Outer Join

后端 未结 16 1550
既然无缘
既然无缘 2020-11-21 22:45

I have a list of people\'s ID and their first name, and a list of people\'s ID and their surname. Some people don\'t have a first name and some don\'t have a surname; I\'d l

16条回答
  •  走了就别回头了
    2020-11-21 22:59

    Thank You everybody for the interesting posts!

    I modified the code because in my case I needed

    • a personalized join predicate
    • a personalized union distinct comparer

    For the ones interested this is my modified code (in VB, sorry)

        Module MyExtensions
            
            Friend Function FullOuterJoin(Of TA, TB, TResult)(ByVal a As IEnumerable(Of TA), ByVal b As IEnumerable(Of TB), ByVal joinPredicate As Func(Of TA, TB, Boolean), ByVal projection As Func(Of TA, TB, TResult), ByVal comparer As IEqualityComparer(Of TResult)) As IEnumerable(Of TResult)
                Dim joinL =
                    From xa In a
                    From xb In b.Where(Function(x) joinPredicate(xa, x)).DefaultIfEmpty()
                    Select projection(xa, xb)
                Dim joinR =
                    From xb In b
                    From xa In a.Where(Function(x) joinPredicate(x, xb)).DefaultIfEmpty()
                    Select projection(xa, xb)
                Return joinL.Union(joinR, comparer)
            End Function
        End Module
    
        Dim fullOuterJoin = lefts.FullOuterJoin(
            rights,
            Function(left, right) left.Code = right.Code And (left.Amount [...] Or left.Description.Contains [...]),
            Function(left, right) New CompareResult(left, right),
            New MyEqualityComparer
        )
    
        Public Class MyEqualityComparer
            Implements IEqualityComparer(Of CompareResult)
    
            Private Function GetMsg(obj As CompareResult) As String
                Dim msg As String = ""
                msg &= obj.Code & "_"
                [...]
                Return msg
            End Function
    
            Public Overloads Function Equals(x As CompareResult, y As CompareResult) As Boolean Implements IEqualityComparer(Of CompareResult).Equals
                Return Me.GetMsg(x) = Me.GetMsg(y)
            End Function
    
            Public Overloads Function GetHashCode(obj As CompareResult) As Integer Implements IEqualityComparer(Of CompareResult).GetHashCode
                Return Me.GetMsg(obj).GetHashCode
            End Function
        End Class
    

提交回复
热议问题