Sorting a collection

Sorting a collection

Old forum URL: forums.lhotka.net/forums/t/1551.aspx


Brownpa1 posted on Friday, October 20, 2006

I  created a collection called m_colLogEntrys.  Each time a user creates or updates an existing record in the Windows Form, I am adding to the m_colLogEntrys collection a log note indicating the date and time and what change or what object was created.  Each time I add to that collection, I would like to sort that collection in decending order based on DateTime.  I have been searching to try to find out how I can do this, but cannot find anything.  Can anyone help?

Here is part of my code:

Dim logentry as LogEntry

'This goes to the LogEntry class and creates the new logentry
logentry = COLibrary.LogEntry.GetNewLogEntry(m_guidId, sbText.ToString, LogSource, LogType)

'This adds the new log entry to my collection
m_colLogEntrys.Add(logentry)

'I would like to sort after a new log entry has been added to the collection
???? m_colLogEntrys.Sort??????

Thank you in advance for you help.

 

Brian Criswell replied on Friday, October 20, 2006

You can use either the stock SortedBindingList that comes with CSLA or ObjectListView which is in the CSLA contrib project.  In either case you add the list to the view and then have the UI (DataGridView, ComboBox, BindingSource, etc.) use the view as the data source.  In the case of SortedBindingList you will need to ask the view to re-sort itself whenever you make a change.

Brownpa1 replied on Friday, October 20, 2006

Thank you, that worked.  Instead of using it in my UI, I decided to use it in my LogEntrys Class.  Here is the code if anyone is interest

Public Function LogEntrysSorted() As SortedBindingList(Of LogEntry)

   'Converting LogEntrys(Me) collection from a BusinessListBase to a SortedBindingList
   'then sorting the list and pass the sorted list out for use.
   Dim sortedList As New SortedBindingList(Of LogEntry) _
   (CType Me   Global.System.Collections.Generic.IList(Of Global.COLibrary.LogEntry)))

   'sorted by the DateTimeStamp property in LogEntry
   sortedList.ApplySort("DateTimeStamp", ListSortDirection.Descending)

   Return sortedList
End Function

Copyright (c) Marimer LLC