I often need to perform LinQ queries to get distinct items from a IEnumerable based on one of its properties. I would like to know if this is a good way to wrap this operation:

<Extension()> Function DistinctOn(Of T)(iet As IEnumerable(Of T),
                                        identity_property As Func(Of T, Object)
                                       ) As IEnumerable(Of T)
    Return iet.GroupBy(identity_property).Select(Function(g) g.First)
End Function

Using example (pastas is a IEnumerable of Newtonsoft.Json.Linq.JObject):

Dim dpastas = pastas.DistinctOn(Function(jo) jo.Value(Of Integer)("id")).ToArray

It works Ok, but I'd like to know if it is good code also. Thank you very much!


That is a good definition for an IQueryable but I believe it is better to implement the operation directly for an IEnumerable (note: I don't use VB, so translated from C#):

<Extension()> Public Iterator Function DistinctBy(Of T, TKey)(src As IEnumerable(Of T), keyFun As Func(Of T, TKey)) As IEnumerable(Of T)
    Dim seenKeys As New HashSet(Of TKey)()
    For Each e As T In src
        If seenKeys.Add(keyFun(e)) Then
            Yield e
        End If
End Function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.