Ok it was an adventure, but this are my results:
The existing Sum extensions only provide basic types as results, therefore need a selector. You found that one out, ok.
Now next step for me was to write my own extension supporting your needs.
So i was looking exactly for what you suggested, an interface that requires the implementing class to have an operator of any kind.
Well there isn't any. You also cannot define such an interface yourself, as operators by nature are static and cannot be overridable.
So next step is to extend sum by a generic type that constrains itself to the type which does have an operator.
Turns out you cannot constrain a generic type to a structure.
So here the code that i got working
So as i understand you wanted to do something like this:
Public Class MainClass
' ...
Public Shared Sub Test()
Dim lsta As New List(Of SomeClass)(New SomeClass() {
New SomeClass(5, 10, 2.5),
New SomeClass(7, 23, 1.2)
}
)
Dim sum As SomeClass = lsta.Sum(Of SomeClass)()
End Sub
' ...
End Class
Now your structure is gonna have to be a class, such as this:
Public Class SomeClass
Public Sub New(x As Int32, y As Int32, c As Double)
m_iX = x
m_iY = y
m_fC = c
End Sub
Private m_iX As Int32
Private m_iY As Int32
Private m_fC As Double
Public ReadOnly Property X
Get
Return m_iX
End Get
End Property
Public ReadOnly Property Y
Get
Return m_iY
End Get
End Property
Public ReadOnly Property C
Get
Return m_fC
End Get
End Property
' Custom operator:
Public Shared Operator +(a As SomeClass, b As SomeClass) As SomeClass
Return New SomeClass(a.X + b.X, a.Y + b.Y, a.C * b.C)
End Operator
' This is coming in handy for initializing the first element in your sum
Public Shared Function NeutralElement() As SomeClass
Return New SomeClass(0, 0, 1)
End Function
End Class
And finally here the extension:
Public Module ListExtension
<Extension()> _
Public Function Sum(Of T As SomeClass)(source As IEnumerable(Of SomeClass)) As SomeClass
' Note we have to constain T to SomeClass (also SomeClass cannot be a Structure :))
Dim returnValue As T = SomeClass.NeutralElement()
For Each el As T In source
returnValue = returnValue + el
Next
Return returnValue
End Function
End Module
I hope this cleared out some issues, ask any questions and,
... have fun implementing it!