Jan 312014
 

I knew that LINQPad was good, but hadn’t realised that in addition to LINQ proper, one can write whole programs, complete with generics:

Function Rank(Of T As {IComparable(Of T)})(items As IEnumerable(Of T), item As T) As Integer

   Dim ranked = From i In items
                Order By i
                Select New With {
                   .key = i,
                   .ranking = (From r In items
                               Where r.CompareTo(i) < 0).Count + 1}

   Return (From i In ranked
           Where i.key.CompareTo(item) = 0
           Select i.ranking).Single

End Function
        
Sub Main()
   Dim l As New list(Of Integer) From {9, 1, 3, 8, 4, 6}
   Dim r As Integer = rank(Of Integer)(l, 6)
   console.write("6 is the " & r & "th element of ")
   For Each n As Integer In l.orderby(Function(x) x)
       console.write(n & " ")
   Next
   console.writeline()
End Sub

which correctly prints
6 is the 4th element of
1 3 4 6 8 9

To say that I’m impressed is a vast understatement.

  3 Responses to “LINQPad is even better than I thought”

  1. Good improvement. Which gives

    Function Rank(Of T As IComparable)(list As IEnumerable(Of T), item As T) As Integer
    Return list.Count(Function(x) x.CompareTo(item) < 0) + 1 End Function Public Sub Main() Dim l = New Integer() {9, 1, 3, 8, 4, 6} Console.WriteLine("6 is the " & Rank(l,6) & "th element of ") Console.WriteLine([String].Join(" ", l)) End Sub 6 is the 4th element of 9 1 3 8 4 6

  2. Sorry, to give the exact same output, the last line of that Main should be :


    Console.WriteLine(String.Join(" ", l.OrderBy(x => x)));

  3. Even more impressive : http://dotnetfiddle.net/3ZGeJ1

    Removing curly braces and semicolons is left as an exercise to the reader 😉

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*