Question Get record with MIN value for one field

mysiar

Member
Joined
Mar 10, 2009
Messages
7
Programming Experience
Beginner
Hi
I have data with fields: ln, pn, idx, x, y and would like to get record with MIN pn.

I got this from MSDN examples
VB.NET:
Dim min = (From p In points Select p.pn).Min()

But this returns only MIN pn not the whole record.

I got it around by
VB.NET:
Dim min = (From p In points Select p.pn).Min()
Dim s = From p In points Where p.pn = min Select p
but would like to have it all done in one step


Could anybody help me with it ?

Regards
Piotr
 
Last edited:
It is a bit messy, but ....

Dim s = From p In points Where p.pn = (From p In points Select p.pn).Min()
 
I also can't think of a way to avoid a two pass doing this with Linq, here's a variant that I think reads better, it uses the Min extension with a transformation function to find the minimum pn and selects from points all that has this minimum value:
VB.NET:
Dim min = From p In points Select p Where p.pn = points.Min(Function(px) px.pn)
If you wanted pn as default sort comparer for the Record you could implement IComparable like this:
VB.NET:
Structure Record
    Implements IComparable(Of Record)

    Public ln, pn, idx, x, y As Integer

    Public Function CompareTo(ByVal other As Record) As Integer Implements System.IComparable(Of Record).CompareTo
        Return Me.pn.CompareTo(other.pn)
    End Function
End Structure
The Min extension would then use this comparer when selecting:
VB.NET:
Dim min = points.Min
Similar you can sort the array/collection with various custom Comparisons then get the first/last item:
VB.NET:
Array.Sort(points, Function(x, y) x.pn.CompareTo(y.pn)) 'for array
' points.Sort(Function(x, y) x.pn.CompareTo(y.pn)) 'for list/collection

Dim min = points.First
 
Actually, if you know there is only going to be one, you could do

Dim s = (From p in points Order by p.pn Asc).First

and if you particularly need it to be as an IEnumerable...

Dim s = New WhateverTheClassIs(){(From p in points Order by p.pn Asc).First}

messy again, but all ideas that might help
 
wizzardmr42 said:
Dim s = (From p in points Order by p.pn Asc).First
of course... you can also sort with the Linq query, I didn't think about that.
 
Back
Top