Question

Sort people in an array

Asked by: keessef

Hi,

Sorry for this 'newbie' question but i'm struggeling with vb.net after a good life in PHP programming..

Question:

User must be able to put in a list of people..
I've got 4 fields, Name, First name, Date of Birth, Dath of employment
So i've got 4 fields on a form, and a button called ADD
What is the best way to 'store' those people? In an array? Because after the 'user' has entered the people, i want to be able to sort people on Employment date or Date of birth and split them out in several 'groups'.
Also, the user must be able to store and retrieve the 'list' in a file (xml?)
Can i do the above without database?

Please provide me with some samplecode..

Regards,

Frank

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-04-13 at 13:58:11ID21813352
Tags

samplecode

Topic

Microsoft Visual Basic.Net

Participating Experts
2
Points
250
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. sort an array
    Array ( [0] => Array ( [news] => [item] => [id] => 1 [title] => XML [user] => Kiros [content] => Dit is een nieuwsbericht gelezen uit een xml bestand, en ik voeg er nu wat onzin aan toe, omdat ik wil zien hoe de opmaak is met meer tekst, het kan namelijk ...
  2. Array sort in php
    $oldarray=array( 1=>array("A"=>"mouse", "B"=>33), 2=>array("A"=>"cat", "B"=>55), 3=>array("A"=>"dog", "B"=>77) ); I need to sort this array on the value of ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: bisonfur37Posted on 2006-04-13 at 14:41:50ID: 16449717

Public Class PersonComparer
    Implements IComparer

    Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
        If Not (TypeOf x Is Person) Then Throw New ArgumentException("Invalid comparison", "x")
        Return DirectCast(x, Person).CompareTo(y)
    End Function
End Class

Public Class Person
    Implements IComparable

    Public Enum ComparableField
        Name
        FirstName
        DateOfBirth
        DateOfEmployment
    End Enum

    Private _name As String
    Private _firstName As String
    Private _dob As DateTime
    Private _doe As DateTime
    Private Shared _comparisonField As ComparableField

    Friend Shared Property ComparisonField() As ComparableField
        Get
            Return _comparisonField
        End Get
        Set(ByVal Value As ComparableField)
            _comparisonField = Value
        End Set
    End Property

    Public Property Name() As String
        Get
            Return _name
        End Get
        Set(ByVal Value As String)
            _name = Value
        End Set
    End Property

    Public Property FirstName() As String
        Get
            Return _firstName
        End Get
        Set(ByVal Value As String)
            _firstName = Value
        End Set
    End Property

    Public Property DateOfBirth() As DateTime
        Get
            Return _dob
        End Get
        Set(ByVal Value As DateTime)
            _dob = Value
        End Set
    End Property

    Public Property DateOfEmployment() As DateTime
        Get
            Return _doe
        End Get
        Set(ByVal Value As DateTime)
            _doe = Value
        End Set
    End Property

    Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
        If Not TypeOf obj Is Person Then Throw New ArgumentException("Invalid comparison", "obj")
        Dim otherPerson As Person = obj

        'ToDo: create CompareTo delegate function and create a PersonCompareToFactory class
        Select Case _comparisonField

            Case ComparableField.DateOfBirth
                Return Me.DateOfBirth.CompareTo(otherPerson.DateOfBirth)

            Case ComparableField.DateOfEmployment
                Return Me.DateOfEmployment.CompareTo(otherPerson.DateOfEmployment)

            Case ComparableField.FirstName
                Return Me.FirstName.CompareTo(otherPerson.FirstName)

            Case ComparableField.Name
                Return Me.Name.CompareTo(otherPerson.Name)

        End Select
    End Function

    Public Sub New(ByVal name As String, ByVal firstName As String, ByVal dob As DateTime, ByVal doe As DateTime)
        Me.Name = name
        Me.FirstName = firstName
        Me.DateOfBirth = dob
        Me.DateOfEmployment = doe
    End Sub

    Public Sub New()

    End Sub

End Class

Public Class PersonCollection
    Implements IEnumerable
    Implements ICollection

    Private _people As New ArrayList

    Public Sub Display(ByVal title As String)
        Dim builder As New System.Text.StringBuilder(String.Empty)

        builder.Append("Name | FirstName | DOB | DOE " & vbCrLf & "----------------------------------------------------" & vbCrLf)

        For Each currentPerson As Person In Me
            builder.Append(currentPerson.Name)
            builder.Append(" |  ")
            builder.Append(currentPerson.FirstName)
            builder.Append(" |  ")
            builder.Append(currentPerson.DateOfBirth.ToString("yyyy-MM-dd"))
            builder.Append(" |  ")
            builder.Append(currentPerson.DateOfEmployment.ToString("yyyy-MM-dd"))
            builder.Append(vbCrLf)
        Next

        MsgBox(builder.ToString(), , title)
    End Sub

    Public ReadOnly Property Count() As Integer Implements System.Collections.ICollection.Count

        Get
            Return _people.Count
        End Get

    End Property

    Default Public ReadOnly Property Item(ByVal index As Integer) As Person

        Get

            If index < 0 Or index >= _people.Count Then
                Throw New ArgumentOutOfRangeException("index", index, "The index must be greater than or equal to zero and less than the number of items in the PersonCollection")
            End If

            Return DirectCast(_people(index), Person)
        End Get

    End Property

    Public Sub Add(ByVal thePerson As Person)
        _people.Add(thePerson)
    End Sub

    Public Function GetEnumerator() As System.Collections.IEnumerator _
                                    Implements System.Collections.IEnumerable.GetEnumerator
        Return New PersonCollectionEnumerator(Me)
    End Function

    Public Sub CopyTo(ByVal array As System.Array, ByVal index As Integer) Implements System.Collections.ICollection.CopyTo
        Call _people.CopyTo(array, index)
    End Sub

    Public ReadOnly Property IsSynchronized() As Boolean Implements System.Collections.ICollection.IsSynchronized
        Get
            Return _people.IsSynchronized
        End Get
    End Property

    Public ReadOnly Property SyncRoot() As Object Implements System.Collections.ICollection.SyncRoot
        Get
            Return _people.SyncRoot
        End Get
    End Property

    Public Sub Sort(ByVal sortBy As Person.ComparableField)
        Person.ComparisonField = sortBy
        _people.Sort(New PersonComparer)
    End Sub

    Private Class PersonCollectionEnumerator
        Implements IEnumerator
        Private _index As Integer
        Private _personCol As PersonCollection


        Public Sub New(ByVal Persons As PersonCollection)
            _personCol = Persons
            Me.Reset()
        End Sub

        Public ReadOnly Property Current() As Object Implements System.Collections.IEnumerator.Current

            Get
                Return _personCol.Item(_index)
            End Get

        End Property

        Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
            _index += 1
            Return (_index < _personCol.Count)
        End Function

        Public Sub Reset() Implements System.Collections.IEnumerator.Reset
            _index = -1
        End Sub

    End Class

End Class

Public Class Tester
    Private _people As New PersonCollection

    Private Sub TestPeople()
        _people.Add(New Person("John Doe", "John", DateSerial(1930, 1, 1), DateSerial(2006, 3, 12)))
        _people.Add(New Person("Homer Simpson", "Homer", DateSerial(1955, 3, 1), DateSerial(1987, 2, 12)))
        _people.Add(New Person("Jane Does", "Jane", DateSerial(1973, 8, 8), DateSerial(2006, 3, 20)))

        _people.Sort(Person.ComparableField.Name)
        _people.Display("Sorted  By Name")
        _people.Sort(Person.ComparableField.DateOfBirth)
        _people.Display("Sorted By DOB")
    End Sub

    Shared Sub Main()
        Call New Tester().TestPeople()
    End Sub

End Class

 

by: bisonfur37Posted on 2006-04-13 at 14:46:59ID: 16449744

To write to file (in  pipe-delimted format), add the following method to class PersonCollection

    Public Sub WriteToFile(ByVal path As String)
        Dim builder As New System.Text.StringBuilder(String.Empty)

        builder.Append("Name | FirstName | DOB | DOE " & vbCrLf & "----------------------------------------------------" & vbCrLf)

        For Each currentPerson As Person In Me
            builder.Append(currentPerson.Name)
            builder.Append(" |  ")
            builder.Append(currentPerson.FirstName)
            builder.Append(" |  ")
            builder.Append(currentPerson.DateOfBirth.ToString("yyyy-MM-dd"))
            builder.Append(" |  ")
            builder.Append(currentPerson.DateOfEmployment.ToString("yyyy-MM-dd"))
            builder.Append(vbCrLf)
        Next

        Dim writer As New System.IO.StreamWriter(path)
        writer.Write(builder.ToString())
        writer.Close()
    End Sub


To  write XML instead of pipe-delimted, check out the  documentation for the XmlWriter or XmlDataDocument classes

 

by: AndyAelbrechtPosted on 2006-04-13 at 15:58:34ID: 16450104

'::: to write to XML with bisonfur37's class:

Private xmls as String  'this is the xml scheme file (see below)

Public Sub WriteToXML(ByVal path as String)

        Dim ds As New DataSet()
        ds.ReadXmlSchema(xmls)
        Dim dt As DataTable
        dt = ds.Tables(0)
        Dim values(3) As String

        For Each currentPerson As Person In Me
            values(0) = currentPerson.Name
            values(1) = currentPerson.FirstName
            values(2) = currentPerson.DateOfBirth.ToString("yyyy-MM-dd")
            values(3) = currentPerson.DateOfEmployment.ToString("yyyy-MM-dd")
            dt.Rows.Add(values)
        Next

        dt.WriteXml(path, XmlWriteMode.WriteSchema, True)
End Sub

'::: the XSD file (this file does not have to be this complicated, but it'll provide a very nice XML output file)

<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="DocumentElement" targetNamespace="users_namespace" xmlns:mstns="users_namespace" xmlns="users_namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:element name="DocumentElement" msdata:IsDataSet="true" msdata:Locale="en-US">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="users">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="Name" type="xs:string" minOccurs="0" />
              <xs:element name="FirstName" type="xs:string" minOccurs="0" />
              <xs:element name="DoB" type="xs:string" minOccurs="0" />
              <xs:element name="DoE" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
  </xs:element>
</xs:schema>

 

by: keessefPosted on 2006-04-14 at 06:03:26ID: 16452957

Thanks both for helping me much further.Three questions still (hope you can help)

1 .I've got to do the following:

I must sort the persons into 5 categories:

-15 till 24 years
-25 till 34 years
-35 till 44 years
-45 till 54 years
-55 years and older

The output must be sorted in those 5 categories and it must be sorted per category by date of employment (the last one first..)

2.

How can i display the array in a label? I've got two boxes on the form and a button. When clicked it does this:
 
_people.Add(New Person(txtName.Text, txtFirstname.Text, DateSerial(1930, 1, 1), DateSerial(2006, 3, 12)))

How can i display on the form the whole array (_people) in a label. So everytime  a new person is added there is one extra in the label.

3.

I've got then the whole output in the array in a label (is this the best way?). I want to be able to modify the data in the label so.. i give an example

John Doe John 24-10-1999 26-12-1981
Jim Tayler Jim 1-01-2000 22-08-1965

If i want to modify Jim, i want able to click on it and the data is displayed back in my form fields.

Many Thanks

Frank

 

by: bisonfur37Posted on 2006-04-14 at 07:55:08ID: 16454002

2-3 Use a listbox or  listview control instead of a label (http://www.startvbdotnet.com/controls/listbox.aspx)


1. Your new requirements are moving you closer to needing more advanced external querying capabilities (e.g. SQL. XQuery).  However, using strictly VB.NET I did satisfy your requirements (albeit in a  sloppy, non-extensible way) below:

    Public Class PersonComparer
        Implements IComparer

        Public Function Compare(ByVal x As Object, ByVal y As Object) As Integer Implements System.Collections.IComparer.Compare
            If Not (TypeOf x Is Person) Then Throw New ArgumentException("Invalid comparison", "x")
            Return DirectCast(x, Person).CompareTo(y)
        End Function
    End Class

    Public Class Person
        Implements IComparable

        Public Enum ComparableField
            Name
            FirstName
            DateOfBirth
            DateOfEmployment
            AgeGroupPlusDateOfEmployment
        End Enum

        Private _name As String
        Private _firstName As String
        Private _dob As DateTime
        Private _doe As DateTime
        Private Shared _comparisonField As ComparableField

        Public ReadOnly Property Age() As Long

            Get
                Dim now As DateTime = DateTime.Now
                Dim toReturn As Long = DateDiff(DateInterval.Year, Me.DateOfBirth, now)
                If DateSerial(now.Year, now.Month, now.Day) < DateSerial(now.Year, DateOfBirth.Month, DateOfBirth.Day) Then toReturn -= 1
                Return toReturn
            End Get

        End Property

        Private ReadOnly Property AgeGroup() As String
            Get

                Select Case Me.Age
                    Case 15 - 24
                        Return "A"
                    Case 25 - 34
                        Return "B"
                    Case 35 - 44
                        Return "C"
                    Case 45 - 54
                        Return "D"
                    Case 55 - 1000
                        Return "E"

                End Select

            End Get
        End Property

        Friend Shared Property ComparisonField() As ComparableField
            Get
                Return _comparisonField
            End Get
            Set(ByVal Value As ComparableField)
                _comparisonField = Value
            End Set
        End Property

        Public Property Name() As String
            Get
                Return _name
            End Get
            Set(ByVal Value As String)
                _name = Value
            End Set
        End Property

        Public Property FirstName() As String
            Get
                Return _firstName
            End Get
            Set(ByVal Value As String)
                _firstName = Value
            End Set
        End Property

        Public Property DateOfBirth() As DateTime
            Get
                Return _dob
            End Get
            Set(ByVal Value As DateTime)
                _dob = Value
            End Set
        End Property

        Public Property DateOfEmployment() As DateTime
            Get
                Return _doe
            End Get
            Set(ByVal Value As DateTime)
                _doe = Value
            End Set
        End Property

        Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
            If Not TypeOf obj Is Person Then Throw New ArgumentException("Invalid comparison", "obj")
            Dim otherPerson As Person = obj

            'ToDo: create CompareTo delegate function and create a PersonCompareToFactory class
            Select Case _comparisonField

                Case ComparableField.DateOfBirth
                    Return Me.DateOfBirth.CompareTo(otherPerson.DateOfBirth)

                Case ComparableField.DateOfEmployment
                    Return Me.DateOfEmployment.CompareTo(otherPerson.DateOfEmployment)

                Case ComparableField.FirstName
                    Return Me.FirstName.CompareTo(otherPerson.FirstName)

                Case ComparableField.Name
                    Return Me.Name.CompareTo(otherPerson.Name)

                Case ComparableField.AgeGroupPlusDateOfEmployment

                    If Me.AgeGroup = otherPerson.AgeGroup Then
                        Return Me.DateOfEmployment.CompareTo(otherPerson.DateOfEmployment)

                    Else
                        Return Me.AgeGroup.CompareTo(otherPerson.AgeGroup)

                    End If

            End Select
        End Function

        Public Sub New(ByVal name As String, ByVal firstName As String, ByVal dob As DateTime, ByVal doe As DateTime)
            Me.Name = name
            Me.FirstName = firstName
            Me.DateOfBirth = dob
            Me.DateOfEmployment = doe
        End Sub

        Public Sub New()

        End Sub

    End Class

    Public Class PersonCollection
        Implements IEnumerable
        Implements ICollection

        Private _people As New ArrayList

        Public Sub Display(ByVal title As String)
            Dim builder As New System.Text.StringBuilder(String.Empty)

            builder.Append("Name | FirstName | DOB | DOE " & vbCrLf & "----------------------------------------------------" & vbCrLf)

            For Each currentPerson As Person In Me
                builder.Append(currentPerson.Name)
                builder.Append(" |  ")
                builder.Append(currentPerson.FirstName)
                builder.Append(" |  ")
                builder.Append(currentPerson.DateOfBirth.ToString("yyyy-MM-dd"))
                builder.Append(" |  ")
                builder.Append(currentPerson.DateOfEmployment.ToString("yyyy-MM-dd"))
                builder.Append(vbCrLf)
            Next

            MsgBox(builder.ToString(), , title)
        End Sub

        Public ReadOnly Property Count() As Integer Implements System.Collections.ICollection.Count

            Get
                Return _people.Count
            End Get

        End Property

        Default Public ReadOnly Property Item(ByVal index As Integer) As Person

            Get

                If index < 0 Or index >= _people.Count Then
                    Throw New ArgumentOutOfRangeException("index", index, "The index must be greater than or equal to zero and less than the number of items in the PersonCollection")
                End If

                Return DirectCast(_people(index), Person)
            End Get

        End Property

        Public Sub Add(ByVal thePerson As Person)
            _people.Add(thePerson)
        End Sub

        Public Function GetEnumerator() As System.Collections.IEnumerator _
                                        Implements System.Collections.IEnumerable.GetEnumerator
            Return New PersonCollectionEnumerator(Me)
        End Function

        Public Sub CopyTo(ByVal array As System.Array, ByVal index As Integer) Implements System.Collections.ICollection.CopyTo
            Call _people.CopyTo(array, index)
        End Sub

        Public ReadOnly Property IsSynchronized() As Boolean Implements System.Collections.ICollection.IsSynchronized
            Get
                Return _people.IsSynchronized
            End Get
        End Property

        Public ReadOnly Property SyncRoot() As Object Implements System.Collections.ICollection.SyncRoot
            Get
                Return _people.SyncRoot
            End Get
        End Property

        Public Sub Sort(ByVal sortBy As Person.ComparableField)
            Person.ComparisonField = sortBy
            _people.Sort(New PersonComparer)
        End Sub

        Private Class PersonCollectionEnumerator
            Implements IEnumerator
            Private _index As Integer
            Private _personCol As PersonCollection


            Public Sub New(ByVal Persons As PersonCollection)
                _personCol = Persons
                Me.Reset()
            End Sub

            Public ReadOnly Property Current() As Object Implements System.Collections.IEnumerator.Current

                Get
                    Return _personCol.Item(_index)
                End Get

            End Property

            Public Function MoveNext() As Boolean Implements System.Collections.IEnumerator.MoveNext
                _index += 1
                Return (_index < _personCol.Count)
            End Function

            Public Sub Reset() Implements System.Collections.IEnumerator.Reset
                _index = -1
            End Sub

        End Class

        Public Sub WriteToFile(ByVal path As String)
            Dim builder As New System.Text.StringBuilder(String.Empty)

            builder.Append("Name | FirstName | DOB | DOE " & vbCrLf & "----------------------------------------------------" & vbCrLf)

            For Each currentPerson As Person In Me
                builder.Append(currentPerson.Name)
                builder.Append(" |  ")
                builder.Append(currentPerson.FirstName)
                builder.Append(" |  ")
                builder.Append(currentPerson.DateOfBirth.ToString("yyyy-MM-dd"))
                builder.Append(" |  ")
                builder.Append(currentPerson.DateOfEmployment.ToString("yyyy-MM-dd"))
                builder.Append(vbCrLf)
            Next

            Dim writer As New System.IO.StreamWriter(path)
            writer.Write(builder.ToString())
            writer.Close()
        End Sub

    End Class

    Public Class Tester
        Private _people As New PersonCollection

        Public Sub TestPeople()
            _people.Add(New Person("Harold Zoid", "Bender", DateSerial(1930, 8, 8), DateSerial(2006, 4, 14)))
            _people.Add(New Person("John Doe", "John", DateSerial(1990, 1, 1), DateSerial(2006, 3, 12)))
            _people.Add(New Person("Homer Simpson", "Homer", DateSerial(1989, 3, 1), DateSerial(2004, 2, 12)))
            _people.Add(New Person("Jane Does", "Jane", DateSerial(1989, 8, 8), DateSerial(2002, 3, 20)))
            _people.Add(New Person("Bender Bending Rodriguez", "Bender", DateSerial(1990, 8, 8), DateSerial(2001, 8, 8)))


            _people.Sort(Person.ComparableField.AgeGroupPlusDateOfEmployment)
            _people.Display("Sorted  By Age Group, Date OfEmployment")
        End Sub

        Shared Sub Main()
            Call New SortPeople.Tester().TestPeople()
        End Sub

    End Class

 

by: keessefPosted on 2006-04-16 at 05:21:51ID: 16463985

Hi,

Thanks for the answer.. I'm only getting one error messages on this code:

 Private ReadOnly Property AgeGroup() As String
        Get
            Select Case Me.Age
                Case 15 - 24
                    Return "A"
                Case 25 - 34
                    Return "B"
                Case 35 - 44
                    Return "C"
                Case 45 - 54
                    Return "D"
                Case 55 - 1000
                    Return "E"

            End Select

        End Get
    End Property

Warning      1      Property 'AgeGroup' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.      

Help! ;-)

Regards,

Frank

 

by: keessefPosted on 2006-04-16 at 05:48:48ID: 16464063

Hi,

Checked it again but the output is also wrong.. I don't no how it's sorted ;-)

I get in the code another error messages:

(this is in the class Tester.vb)

Call New SortPeople.Tester().TestPeople()

Error message:

Error      2      Type 'SortPeople.Tester' is not defined.

Regards,

Frank

 

by: keessefPosted on 2006-04-16 at 06:58:31ID: 16464260

Sorry, Third comment:

If you take out the SortPeople and leave it as Tester().Testpeople() it's working. Don't now if it's correct.

This is my list:
 _people.Add(New Person("Harold Zoid", "Bender", DateSerial(1930, 8, 8), DateSerial(2006, 4, 14)))
        _people.Add(New Person("John Doe", "John", DateSerial(1990, 1, 1), DateSerial(2006, 3, 12)))
        _people.Add(New Person("Homer Simpson", "Homer", DateSerial(1989, 3, 1), DateSerial(2004, 2, 12)))
        _people.Add(New Person("Jane Does", "Jane", DateSerial(1989, 8, 8), DateSerial(2002, 3, 20)))
        _people.Add(New Person("Bender Bending Rodriguez", "Bender", DateSerial(1990, 8, 8), DateSerial(2001, 8, 8)))
        _people.Add(New Person("Bender Bending Marinissen", "Jan-Willem", DateSerial(1931, 8, 8), DateSerial(2003, 3, 8)))
        _people.Add(New Person("Bender Bending Rodriguez", "Joke", DateSerial(1982, 8, 5), DateSerial(2005, 12, 8)))
        _people.Add(New Person("Bender Bending Rodriguez", "Richard", DateSerial(1976, 2, 8), DateSerial(2002, 1, 18)))
        _people.Add(New Person("Bender Bending Rodriguez", "Frank", DateSerial(1975, 3, 8), DateSerial(1988, 2, 21)))

This is the output now:

Bender Bending Rodriguez |  Frank |  1975-03-08 |  1988-02-21
Bender Bending Rodriguez |  Bender |  1990-08-08 |  2001-08-08
Bender Bending Rodriguez |  Richard |  1976-02-08 |  2002-01-18
Jane Does |  Jane |  1989-08-08 |  2002-03-20
Bender Bending Marinissen |  Jan-Willem |  1931-08-08 |  2003-03-08
Homer Simpson |  Homer |  1989-03-01 |  2004-02-12
Bender Bending Rodriguez |  Joke |  1982-08-05 |  2005-12-08
John Doe |  John |  1990-01-01 |  2006-03-12
Harold Zoid |  Bender |  1930-08-08 |  2006-04-14


Question number 2

How can i access in the code the categories: So display only the people in the categorie of: 45-54 years.


Question number 3

I found this in the code:

   Public ReadOnly Property Age() As Long

        Get
            Dim now As DateTime = DateTime.Now
            Dim toReturn As Long = DateDiff(DateInterval.Year, Me.DateOfBirth, now)
            If DateSerial(now.Year, now.Month, now.Day) < DateSerial(Now.Year, DateOfBirth.Month, DateOfBirth.Day) Then toReturn -= 1
            Return toReturn
        End Get

    End Property

Original line:

     If DateSerial(now.Year, now.Month, now.Day) < DateSerial(Now.Year, DateOfBirth.Month, DateOfBirth.Day) Then toReturn -= 1

Shouldn't this be:
                                                                                             
  If DateSerial(now.Year, now.Month, now.Day) < DateSerial(DateOfBirth.Year, DateOfBirth.Month, DateOfBirth.Day) Then toReturn -= 1

Thanks again for your help!!! Happy easter!

Regards,

Frank

 

by: bisonfur37Posted on 2006-04-16 at 11:06:09ID: 16465125

1.  To remove the warning, change "Case 55-1000" to "Case Else"

2.  My classes existed in  namespace "SortPeople",  which you correctly removed from the function call

3.  OK... found a major bug that causes incorrect sorting  --> in property AgeGroup, replace the "-" character with the word  "To" (e.g. "Case 55 - 1000" becomes "Case 55 To  1000"). Sorry for the careless mistake

4. First you  should change the access modifier for  property AgeGroup  from  "Private"  to "Public." That will allow you to access the property as normal such as "_people(0).AgeGroup". Note that this will property returns a string representing the person's Age  Group as defined in the code (I recommend making these constants). To access only people  in  a certain age group, loop through the collection and select only those in the age group:

            For Each currentPerson As Person In _people

                If currentPerson.AgeGroup = "A" Then
                    'logic  for people aged 15-24
                End If

            Next


5. Although it looks odd, the code for the Age property is actually (pretty much) correct. The problem is that the built-in DateDiff method will always "round up" the number of years between the two date paramaeters, so that if you were born on 2005-12-31 and today is 2006-04-16, DateDiff will  return 1.  The line of code in question adjusts for this  by subtracting one from the return value if the person's birthday has not occurred yet in the current year. The  logic is not precise --  for example, DateSerial(Now.Year, DateOfBirth.Month, DateOfBirth.Day) can throw an error if DateOfBirth.Month = February, DateOfBirth.Day = 29, and Now.Year is  not a leap year. But  I will  leave it as an exercise for you to clean up the  logic...

 

by: keessefPosted on 2006-04-17 at 08:17:46ID: 16469668

Thanks!! Great it works!

One small question before I rewared you the points; Date of Employment must be sorted on the people who where last employed..(so last one's employed first).... (Sorry ;-) )

Thanks for your help again!! Really good!

Regards,

Frank

 

by: bisonfur37Posted on 2006-04-17 at 08:35:15ID: 16469819

assuming you want to sort Date of Employment (DOE) descending when sorting by either just DOE or DOE plus Age Range,  change method Person.CompareTo to the following:

        Public Function CompareTo(ByVal obj As Object) As Integer Implements System.IComparable.CompareTo
            If Not TypeOf obj Is Person Then Throw New ArgumentException("Invalid comparison", "obj")
            Dim otherPerson As Person = obj

            'ToDo: create CompareTo delegate function and create a PersonCompareToFactory class
            Select Case _comparisonField

                Case ComparableField.DateOfBirth
                    Return Me.DateOfBirth.CompareTo(otherPerson.DateOfBirth)

                Case ComparableField.DateOfEmployment
                    'Return Me.DateOfEmployment.CompareTo(otherPerson.DateOfEmployment)
                    Return otherPerson.DateOfEmployment.CompareTo(Me.DateOfEmployment)

                Case ComparableField.FirstName
                    Return Me.FirstName.CompareTo(otherPerson.FirstName)

                Case ComparableField.Name
                    Return Me.Name.CompareTo(otherPerson.Name)

                Case ComparableField.AgeGroupPlusDateOfEmployment

                    If Me.AgeGroup = otherPerson.AgeGroup Then
                        'Return Me.DateOfEmployment.CompareTo(otherPerson.DateOfEmployment)
                        Return otherPerson.DateOfEmployment.CompareTo(Me.DateOfEmployment)

                    Else
                        Return Me.AgeGroup.CompareTo(otherPerson.AgeGroup)

                    End If

            End Select

        End Function

 

by: keessefPosted on 2006-04-19 at 12:35:40ID: 16491537

Hi bisonfur37,

Thanks again for helping me out.. I hope you can help me for the last time (i've already rewarded the points)..

I'm trying to search in the array..

I've got the following line:

Dim index as Integer = Array.IndexOf(_person,"John")

This is not going to work.. Can you please provide me with some more detail how i can access the Array.. (sorry i'm still now 2/3 weeks busy with vb.net)..

Thank you very much!

Frank

 

by: bisonfur37Posted on 2006-04-19 at 14:14:04ID: 16492589

given the current structure, the easiest way is to just  loop through all elements in the collection:

            Dim index As Integer = -1

            For i As Integer = 0 To _people.Count - 1

                If String.Compare(_people(i).Name, "john", True) = 0 Then
                    index = i
                    Exit For
                End If

            Next

 

by: keessefPosted on 2006-04-26 at 07:13:52ID: 16544025

Hi Bisofur37,

I hope you can shed your light on this:

I'm adding people into the array by:

Example (page2)
_people.Add(New Person("John Doe", "John", DateSerial(1990, 1, 1), DateSerial(2006, 3, 12)))
_people.Sort(Person.ComparableField.AgeGroupPlusDateOfEmployment)

On another page (page 3) i'm doing this:
 Private Sub stap3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        For Each currentPerson As Person In _people

            If currentPerson.AgeGroup = "A" Then
                ListBox1.Items.Add(currentPerson.Name)
            End If
            If currentPerson.AgeGroup = "B" Then
                ListBox2.Items.Add(currentPerson.Name)
            End If
            If currentPerson.AgeGroup = "C" Then
                ListBox3.Items.Add(currentPerson.Name)
            End If
            If currentPerson.AgeGroup = "D" Then
                ListBox4.Items.Add(currentPerson.Name)
            End If
            If currentPerson.AgeGroup = "E" Then
                ListBox5.Items.Add(currentPerson.Name)
            End If


        Next
    End Sub

If i'm doing it on the same 'page', adding, sorting and displaying everything works fine.. Can you give me a hint?

Thanks,

Frank

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...