0

I have a table with 2 columns clmAge and clmPrice like

Age Price
1  ,  100 
2  ,  100
3  ,  150
4  ,  150
5  ,  100
6  ,  100
7  ,  100

Prices might be the same for different ages, and I need the min and max age that are for all consecutive ages with the same price. I need to group my data so my results are like:

1-2 , 100  
3-4 , 150
5-7 , 100
ekad
  • 14,436
  • 26
  • 44
  • 46
Yannis
  • 37
  • 9
  • When you say "I have a table", what do you mean? Is it in a text file, a database, a list of tuples? Hard to answer the question without a little more info. – Darryl Sep 17 '15 at 17:49

1 Answers1

1

Try this

Imports System.Data
Module Module1
    Sub Main()
        Dim dt As New DataTable()
        dt.Columns.Add("clmAge", GetType(Integer))
        dt.Columns.Add("clmPrice", GetType(Integer))

        dt.Rows.Add(New Object() {1, 100})
        dt.Rows.Add(New Object() {2, 100})
        dt.Rows.Add(New Object() {3, 150})
        dt.Rows.Add(New Object() {4, 150})
        dt.Rows.Add(New Object() {5, 100})
        dt.Rows.Add(New Object() {6, 100})
        dt.Rows.Add(New Object() {7, 100})

        Dim oldPrice = 0
        Dim groups As New List(Of Group)
        Dim newGroup As Group = Nothing
        For Each row As DataRow In dt.AsEnumerable()

            If row("clmPrice") <> oldPrice Then
                newGroup = New Group()
                groups.Add(newGroup)
                newGroup.minAge = row("clmAge")
                newGroup.price = row("clmPrice")
            End If
            newGroup.maxAge = row("clmAge")
            oldPrice = row("clmPrice")
        Next row
    End Sub
End Module
Public Class Group
    Public minAge As Integer
    Public maxAge As Integer
    Public price As Integer
End Class
Enigmativity
  • 113,464
  • 11
  • 89
  • 172
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • many thanks #jdweng. i was stuck to make it using linq but this is far more straight forward. – Yannis Sep 18 '15 at 05:39