473,694 Members | 2,850 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Sorting a System.Collecti ons.ObjectModel .Collection

How do you sort a generic collection derived from
System.Collecti ons.ObjectModel .Collection?

Thanks in advance,
- Arthur Dent
Mar 22 '06 #1
6 7209
Hi,

I made this Generic 'base' List that I use to store collections of objects.
It allows me to sort them, show them in a datagrid/datagridview, search on
propertys, and some stuff to save all the items in the class, see if they
have changes etc. Just pick out the things you need :-)

I hope this helps.

Pieter

Option Explicit On

Imports System.Windows. Forms

Imports System.Componen tModel
Imports System.Collecti ons
Imports System.Collecti ons.Specialized

Public Class clsBaseList(Of T As clsBaseClass)
Inherits BindingList(Of T)
Implements IComponent

Public Sub New()
MyBase.New()
Me.AllowNew = False
Me.AllowRemove = True
End Sub

#Region "IComponent Implementation"
Private m_Site As ISite = Nothing
Public Event Disposed(ByVal sender As Object, ByVal e As
System.EventArg s) _
Implements System.Componen tModel.ICompone nt.Disposed

Protected Property Site() As System.Componen tModel.ISite Implements _
System.Componen tModel.ICompone nt.Site
Get
Return m_Site
End Get
Set(ByVal Value As System.Componen tModel.ISite)
m_Site = Value
End Set
End Property

Public Sub Dispose() Implements System.IDisposa ble.Dispose
Me.Items.Clear( )
RaiseEvent Disposed(Me, System.EventArg s.Empty)
End Sub
#End Region

#Region "IBindingLi st Sorting Features"
Private m_SupportsSorti ng As Boolean = True
Private m_SortProperty As PropertyDescrip tor
Private m_SortDirection As ListSortDirecti on
Private m_OriginalList As ArrayList

Protected Overrides ReadOnly Property SupportsSorting Core() As Boolean
Get
Return m_SupportsSorti ng
End Get
End Property
Protected Overrides ReadOnly Property SortDirectionCo re() As
System.Componen tModel.ListSort Direction
Get
Return m_SortDirection
End Get
End Property

Protected Overrides ReadOnly Property SortPropertyCor e() As
System.Componen tModel.Property Descriptor
Get
Return m_SortProperty
End Get
End Property

Protected Overrides ReadOnly Property IsSortedCore() As Boolean
Get
Return m_SortProperty Is Nothing
End Get
End Property

Private Sub SaveList()
m_OriginalList = New ArrayList(Me.It ems)
End Sub

Private Sub ResetList(ByVal NewList As ArrayList)
Me.ClearItems()
For Each m_T As T In NewList
Me.Add(m_T)
Next
End Sub

Private Sub DoSort()
Dim m_Comparer As New clsListComparer (m_SortProperty ,
m_SortDirection )
Dim m_SortList As New ArrayList(Me.It ems)
m_SortList.Sort (m_Comparer)
ResetList(m_Sor tList)
End Sub

Protected Overrides Sub ApplySortCore(B yVal prop As
System.Componen tModel.Property Descriptor, ByVal direction As
System.Componen tModel.ListSort Direction)
'toegevoegd door Pieter want sorteerde enkel Ascending in een
DataGridView...
If m_SortProperty IsNot Nothing Then
If (m_SortProperty .Name = prop.Name) And (m_SortDirectio n =
direction) Then
'wisselen!
direction = (direction + 1) Mod 2
End If
End If

m_SortProperty = prop
m_SortDirection = direction
If (m_OriginalList Is Nothing) Then
SaveList()
End If
DoSort()
End Sub

Protected Overrides Sub RemoveSortCore( )
ResetList(m_Ori ginalList)
m_SortDirection = Nothing
m_SortProperty = Nothing
End Sub
#End Region

#Region "Private Variabel Declarations"
Private m_blnSavedSucce sfull As Boolean
Private m_blnDeletedSuc cesfull As Boolean
Private m_blnCatchChang es As Boolean = True
Private m_blnHasChanges As Boolean = False
Private m_strEntiteName As String = "entité"
Private m_strEntiteCe As String = "cette"
Private m_blnSelected As Boolean = True
Private m_blnFilling As Boolean = False
Private m_blnThrowEvery ChangesEvent As Boolean = False
#End Region

#Region "Protected Variabel Declarations"

#End Region

#Region "Protected Methods"
''' <name>Sub SaveBegin</name>
''' <summary>
''' Method to call at the beginning of a Save.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Protected Sub SaveBegin()
Me.SavedSuccesf ull = True
End Sub

''' <name>Sub SaveEnd</name>
''' <summary>
''' Method to call at the end of a Save. Calls
SetClassToUncha ngedState(). Must only be called on SavedSuccesfull .
''' </summary>
''' <history>
''' PCO Created
''' </history>
Protected Sub SaveEnd()
If Me.SavedSuccesf ull Then
'Après qu'on a sauvegarder tout les info: donne la message qu'on
a tout bien sauvegarder et qu'on peut remttre le control dans un état "pas
de changements"
SetCollectionTo UnchangedState( )
Else
'tell the user that his class wasn't saved succesfully!
End If
'raise the event that the save has ended
'RaiseEvent SaveHasEnded(Me , EventArgs.Empty )
End Sub

''' <name>Sub DeleteBegin</name>
''' <summary>
''' Method to call at the beginning of a Delete.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Protected Sub DeleteBegin()
Me.DeletedSucce sfull = True
End Sub
#End Region

#Region "Public Propertys"
''' <name>Propert y SavedSuccesfull </name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique si la classe a été sauvegarder avec succès.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property SavedSuccesfull () As Boolean
Get
Return m_blnSavedSucce sfull
End Get
Set(ByVal value As Boolean)
m_blnSavedSucce sfull = value
End Set
End Property

''' <name>Propert y DeletedSuccesfu ll</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique si la classe a été supprimé avec succès.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property DeletedSuccesfu ll() As Boolean
Get
Return m_blnDeletedSuc cesfull
End Get
Set(ByVal value As Boolean)
m_blnDeletedSuc cesfull = value
End Set
End Property

''' <name>Propert y CatchChanges</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique si le control doit réagir sur des changements ou pas: par
exemple pas pendant qu'on fait le load d'une entité...
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property CatchChanges() As Boolean
Get
Return m_blnCatchChang es
End Get
Set(ByVal value As Boolean)
m_blnCatchChang es = value
Dim clsI As clsBaseClass
For Each clsI In MyBase.Items
clsI.CatchChang es = m_blnCatchChang es
Next
End Set
End Property

''' <name>Propert y ThrowEveryChang esEvent</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique qu'un evenement doit être raised à chaque changement, ou
seulement le premier fois...
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property ThrowEveryChang esEvent() As Boolean
Get
Return m_blnThrowEvery ChangesEvent
End Get
Set(ByVal value As Boolean)
m_blnThrowEvery ChangesEvent = value
End Set
End Property

'<System.Compon entModel.Defaul tValue(False)> _
Public Event HasChangesEvent As EventHandler(Of HasChangesEvent Args)
''' <name>Propert y HasChanges</name>
''' <returns>Boolea n</returns>
''' <summary>
''' True s'il y a des changements qui se sont passés aux propertys de la
classe.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property HasChanges() As Boolean
Get
Return m_blnHasChanges
End Get
Set(ByVal value As Boolean)
m_blnHasChanges = value
End Set
End Property

''' <name>Propert y EntiteName</name>
''' <returns>String </returns>
''' <summary>
''' Le nom de l'entité de la classe.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property EntiteName() As String
Get
Return m_strEntiteName
End Get
Set(ByVal value As String)
m_strEntiteName = value
End Set
End Property

''' <name>Propert y EntiteCe</name>
''' <returns>String </returns>
''' <summary>
''' CET adresse, CE fournisseur, ...
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property EntiteCe() As String
Get
Return m_strEntiteCe
End Get
Set(ByVal value As String)
m_strEntiteCe = value
End Set
End Property

#End Region

#Region "Base Collection Methods"
''' <name>Functio n TestCloseCollec tion</name>
''' <returns>Intege r</returns>
''' <summary>
''' This Methode tests for unsaved changes when CatchChanges is True,
and ask to save unchanged changes.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Function TestCloseCollec tion() As Integer
If Me.m_blnCatchCh anges And Me.m_blnHasChan ges Then
Dim intA As Integer
intA = MessageBox.Show ("Vous avez fait des changements depuis le
dernier sauvegarde." & vbCrLf & "Est-ce que vous voulez les sauvegarder?",
"Sauvegarde r changements?", MessageBoxButto ns.YesNoCancel,
MessageBoxIcon. Warning)

If intA = vbYes Then
'raise event to save the changes
'RaiseEvent Click_Save()
If Me.Save() Then
'if succesfully saved: class can be
disposed/finalized...
Return vbYes
Else
'if not: don't close it...
Return vbCancel
End If
ElseIf intA = vbNo Then
'if they don't want to save the changes: disable the
changes-handler
Me.CatchChanges = False
Return intA
Else
Return intA
End If
Else
Return vbYes
End If
End Function

''' <name>Functio n Save</name>
''' <returns>Boolea n</returns>
''' <summary>
''' ' Update les changements ou insert les dans la base de données pour
tout les objets dans la collection.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Function Save() As Boolean
Try
Me.SaveBegin()
Dim clsI As clsBaseClass
For Each clsI In MyBase.Items
If Not clsI.Save() Then SavedSuccesfull = False
Next
Catch ex As Exception
'ErrorMessage(e x)
SavedSuccesfull = False
Throw ex
End Try

Me.SaveEnd()
Return SavedSuccesfull
End Function

''' <name>Functio n Delete</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Supprime tout les éléments dans la liste
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Function Delete() As Boolean
Try
Me.DeleteBegin( )
Dim clsI As clsBaseClass
For Each clsI In MyBase.Items
If Not clsI.Delete Then
Me.DeletedSucce sfull = False
Return Me.DeletedSucce sfull
Exit Function
End If
Next

'remove them all
Me.Clear()
Catch ex As Exception
'ErrorMessage(e x)
Me.DeletedSucce sfull = False
Throw ex
End Try

Return Me.DeletedSucce sfull
End Function

''' <name>Functio n Delete</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Deletes a specified Object in the List
''' </summary>
''' <param name="item">ByV al item As T: The item that must be
deleted</param>
''' <history>
''' PCO Created
''' </history>
Public Function Delete(ByVal item As T) As Boolean
Try
Me.DeleteBegin( )
If Not item.Delete Then Me.DeletedSucce sfull = False
Me.Remove(item)
Catch ex As Exception
'ErrorMessage(e x)
Me.DeletedSucce sfull = False
Throw ex
End Try

Return Me.DeletedSucce sfull
End Function

''' <name>Sub SetCollectionTo UnchangedState</name>
''' <summary>
''' Methode qui remets le HasChanges = False et CatchChanges = True
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Sub SetCollectionTo UnchangedState( )
'reset it
CatchChanges = True
HasChanges = False
End Sub

Private Sub OnObjectInListC hangedHandler(B yVal sender As Object, ByVal e
As HasChangesEvent Args)
'always...
''regarde si on n'as pas déjà fait...
''If (Not m_blnHasChanges ) Then 'il y a une valeur qui est changé!
''ok, il y a une valeur changé
HasChanges = True
RaiseEvent HasChangesEvent (sender, e)
''End If
End Sub

Private Sub OnObjectInListS electedChangedH andler(ByVal sender As Object,
ByVal e As HasChangesEvent Args)
'always...
RaiseEvent HasChangesSelec tedEvent(sender , e)
End Sub

Public Event HasChangesSelec tedEvent As EventHandler(Of
HasChangesEvent Args)

''' <name>ReadOnl y Property SelectedCount() </name>
''' <returns>Intege r</returns>
''' <summary>
''' Property qui retourne le nombre d'Items dans la collection qui a le
property Selected = True
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public ReadOnly Property SelectedCount() As Integer
Get
Dim clsB As clsBaseClass
Dim intC As Integer = 0
For Each clsB In MyBase.Items
If clsB.Selected Then
intC += 1
End If
Next
Return intC
End Get
End Property
#End Region

#Region "List Methods"
Public Shadows Sub Add(ByVal item As T)
item.SetClassTo UnchangedState( )
AddHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
AddHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.Add(item )
End Sub

Public Shadows Sub Insert(ByVal index As Integer, ByVal item As T)
item.SetClassTo UnchangedState( )
AddHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
AddHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.Insert(i ndex, item)
End Sub

Public Shadows Sub Clear()
For Each item As clsBaseClass In Me
RemoveHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
RemoveHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
Next
MyBase.Clear()
End Sub

Public Shadows Function Remove(ByVal item As T) As Boolean
RemoveHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
RemoveHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
Return MyBase.Remove(i tem)
End Function

Public Shadows Sub RemoveAt(ByVal index As Integer)
RemoveHandler MyBase.Item(ind ex).HasChangesE vent, AddressOf
OnObjectInListC hangedHandler
RemoveHandler MyBase.Item(ind ex).SelectedCha nged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.RemoveAt (index)
End Sub

'very important, otherwise it will return objects of clsBaseClass, and
not object of T...
Default Public Shadows Property Item(ByVal index As Integer) As T
Get
Return MyBase.Item(ind ex)
End Get
Set(ByVal value As T)
AddHandler value.HasChange sEvent, AddressOf
OnObjectInListC hangedHandler
AddHandler value.SelectedC hanged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.Item(ind ex) = value
End Set
End Property

#End Region

#Region "Searching"
Protected Overrides ReadOnly Property SupportsSearchi ngCore() As Boolean
Get
Return True
End Get
End Property

' Item property descriptor collection cache
Dim pdc As PropertyDescrip torCollection = Nothing

Protected Overrides Function FindCore(ByVal [property] As
PropertyDescrip tor, ByVal key As Object) As Integer
' Specify search columns
If ([property] Is Nothing) Then
Return -1
End If

' Get list to search
Dim items As List(Of T) = Me.Items
' Traverse list for value
For Each item As T In items
' Test column search value
Dim value As String = CStr([property].GetValue(item) )
'If value is the search value, return the
' index of the data item
If (CStr(key) = value) Then
Return IndexOf(item)
End If
Next item
Return -1
End Function

'ByVal [property] As PropertyDescrip tor, ByVal key As Object
Public Function FindItems(ByVal ColumnName As String, ByVal ColumnValue
As Object) As clsBaseList(Of T)
Dim lst As New clsBaseList(Of T)
Dim properties As PropertyDescrip torCollection
Dim myProperty As PropertyDescrip tor

' Specify search columns
If (ColumnName Is Nothing) Then
Return Nothing
End If

' Get list to search
Dim items As List(Of T) = Me.Items
' Traverse list for value
For Each item As T In items
properties = TypeDescriptor. GetProperties(i tem.GetType)
myProperty = properties.Find (ColumnName, False)
' Test column search value
Dim value As String = CStr(myProperty .GetValue(item) )
'If value is the search value, return the
' index of the data item
If (CStr(ColumnVal ue) = value) Then
lst.Add(item)
End If
Next item
Return lst
End Function

Public Function FindItem(ByVal ColumnName As String, ByVal ColumnValue
As Object) As T
Dim properties As PropertyDescrip torCollection =
TypeDescriptor. GetProperties(M e.Items(0).GetT ype)
Dim myProperty As PropertyDescrip tor = properties.Find (ColumnName,
False)
Dim i As Integer = FindCore(myProp erty, ColumnValue)
If i = -1 Then
Return Nothing
Else
Return Me.Item(i)
End If
End Function

Public Function SumItems(ByVal ColumnName As String) As Decimal
Dim properties As PropertyDescrip torCollection
Dim myProperty As PropertyDescrip tor

' Specify search columns
If (ColumnName Is Nothing) Then
Return Nothing
End If

' Get list to search
Dim items As List(Of T) = Me.Items
' Traverse list for value
Dim decSum As Decimal = 0
For Each item As T In items
properties = TypeDescriptor. GetProperties(i tem.GetType)
myProperty = properties.Find (ColumnName, False)
'Dim value As String = CStr(myProperty .GetValue(item) )
decSum += CSng(myProperty .GetValue(item) )
Next item
Return decSum
End Function

#End Region

End Class

Public Class clsListComparer
Implements IComparer

Private m_SortList As ListSortDescrip tionCollection

Public Sub New(ByVal SortProperty As PropertyDescrip tor, ByVal direction
As ListSortDirecti on)
'Create a new list every time
m_SortList = New ListSortDescrip tionCollection( New
ListSortDescrip tion() {New ListSortDescrip tion(SortProper ty, direction)})
End Sub

Public Sub New(ByVal SortList As ListSortDescrip tionCollection)
m_SortList = SortList
End Sub

Private Function CompareSinglePr operty(ByVal x As clsBaseClass, ByVal y
As clsBaseClass, ByVal prop As PropertyDescrip tor, ByVal direction As
ListSortDirecti on) As Integer
Dim result As Integer = 0
Dim directionModifi er As Integer
If (direction = ListSortDirecti on.Ascending) Then
directionModifi er = 1
Else
directionModifi er = -1
End If
If (x Is Nothing) Then
result = -1 * directionModifi er
ElseIf (y Is Nothing) Then
result = 1 * directionModifi er
ElseIf (prop.GetValue( x) < prop.GetValue(y )) Then
result = -1 * directionModifi er
ElseIf (prop.GetValue( x) > prop.GetValue(y )) Then
result = 1 * directionModifi er
Else
result = 0
End If
Return result
End Function

Private Function Compare(ByVal x As Object, ByVal y As Object) As
Integer _
Implements System.Collecti ons.IComparer.C ompare
Dim idx As Integer
Dim result As Integer
If (Not TypeOf x Is clsBaseClass) Then
Throw New ArgumentExcepti on("Unexpected Argument. Arguments
must be of Type ", "x")
End If
If (Not TypeOf y Is clsBaseClass) Then
Throw New ArgumentExcepti on("Unexpected Argument. Arguments
must be of Type ", "y")
End If
For idx = 0 To m_SortList.Coun t - 1
result = CompareSinglePr operty(x, y,
m_SortList(idx) .PropertyDescri ptor, m_SortList(idx) .SortDirection)
If (result <> 0) Then
Exit For
End If
Next
Return result
End Function
End Class

Mar 22 '06 #2
I could do that, but the thing is that that defeats the point of OO. I was
trying to take advantage of the generic collection as a base so i wouldnt
have to reinvent the wheel..... theres a lot of code involved in coding
collection classes.
"Pieter" <pi**********@h otmail.com> wrote in message
news:Ox******** ******@TK2MSFTN GP12.phx.gbl...
Hi,

I made this Generic 'base' List that I use to store collections of
objects. It allows me to sort them, show them in a datagrid/datagridview,
search on propertys, and some stuff to save all the items in the class,
see if they have changes etc. Just pick out the things you need :-)

I hope this helps.

Pieter

Option Explicit On

Imports System.Windows. Forms

Imports System.Componen tModel
Imports System.Collecti ons
Imports System.Collecti ons.Specialized

Public Class clsBaseList(Of T As clsBaseClass)
Inherits BindingList(Of T)
Implements IComponent

Public Sub New()
MyBase.New()
Me.AllowNew = False
Me.AllowRemove = True
End Sub

#Region "IComponent Implementation"
Private m_Site As ISite = Nothing
Public Event Disposed(ByVal sender As Object, ByVal e As
System.EventArg s) _
Implements System.Componen tModel.ICompone nt.Disposed

Protected Property Site() As System.Componen tModel.ISite Implements _
System.Componen tModel.ICompone nt.Site
Get
Return m_Site
End Get
Set(ByVal Value As System.Componen tModel.ISite)
m_Site = Value
End Set
End Property

Public Sub Dispose() Implements System.IDisposa ble.Dispose
Me.Items.Clear( )
RaiseEvent Disposed(Me, System.EventArg s.Empty)
End Sub
#End Region

#Region "IBindingLi st Sorting Features"
Private m_SupportsSorti ng As Boolean = True
Private m_SortProperty As PropertyDescrip tor
Private m_SortDirection As ListSortDirecti on
Private m_OriginalList As ArrayList

Protected Overrides ReadOnly Property SupportsSorting Core() As Boolean
Get
Return m_SupportsSorti ng
End Get
End Property
Protected Overrides ReadOnly Property SortDirectionCo re() As
System.Componen tModel.ListSort Direction
Get
Return m_SortDirection
End Get
End Property

Protected Overrides ReadOnly Property SortPropertyCor e() As
System.Componen tModel.Property Descriptor
Get
Return m_SortProperty
End Get
End Property

Protected Overrides ReadOnly Property IsSortedCore() As Boolean
Get
Return m_SortProperty Is Nothing
End Get
End Property

Private Sub SaveList()
m_OriginalList = New ArrayList(Me.It ems)
End Sub

Private Sub ResetList(ByVal NewList As ArrayList)
Me.ClearItems()
For Each m_T As T In NewList
Me.Add(m_T)
Next
End Sub

Private Sub DoSort()
Dim m_Comparer As New clsListComparer (m_SortProperty ,
m_SortDirection )
Dim m_SortList As New ArrayList(Me.It ems)
m_SortList.Sort (m_Comparer)
ResetList(m_Sor tList)
End Sub

Protected Overrides Sub ApplySortCore(B yVal prop As
System.Componen tModel.Property Descriptor, ByVal direction As
System.Componen tModel.ListSort Direction)
'toegevoegd door Pieter want sorteerde enkel Ascending in een
DataGridView...
If m_SortProperty IsNot Nothing Then
If (m_SortProperty .Name = prop.Name) And (m_SortDirectio n =
direction) Then
'wisselen!
direction = (direction + 1) Mod 2
End If
End If

m_SortProperty = prop
m_SortDirection = direction
If (m_OriginalList Is Nothing) Then
SaveList()
End If
DoSort()
End Sub

Protected Overrides Sub RemoveSortCore( )
ResetList(m_Ori ginalList)
m_SortDirection = Nothing
m_SortProperty = Nothing
End Sub
#End Region

#Region "Private Variabel Declarations"
Private m_blnSavedSucce sfull As Boolean
Private m_blnDeletedSuc cesfull As Boolean
Private m_blnCatchChang es As Boolean = True
Private m_blnHasChanges As Boolean = False
Private m_strEntiteName As String = "entité"
Private m_strEntiteCe As String = "cette"
Private m_blnSelected As Boolean = True
Private m_blnFilling As Boolean = False
Private m_blnThrowEvery ChangesEvent As Boolean = False
#End Region

#Region "Protected Variabel Declarations"

#End Region

#Region "Protected Methods"
''' <name>Sub SaveBegin</name>
''' <summary>
''' Method to call at the beginning of a Save.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Protected Sub SaveBegin()
Me.SavedSuccesf ull = True
End Sub

''' <name>Sub SaveEnd</name>
''' <summary>
''' Method to call at the end of a Save. Calls
SetClassToUncha ngedState(). Must only be called on SavedSuccesfull .
''' </summary>
''' <history>
''' PCO Created
''' </history>
Protected Sub SaveEnd()
If Me.SavedSuccesf ull Then
'Après qu'on a sauvegarder tout les info: donne la message
qu'on a tout bien sauvegarder et qu'on peut remttre le control dans un
état "pas de changements"
SetCollectionTo UnchangedState( )
Else
'tell the user that his class wasn't saved succesfully!
End If
'raise the event that the save has ended
'RaiseEvent SaveHasEnded(Me , EventArgs.Empty )
End Sub

''' <name>Sub DeleteBegin</name>
''' <summary>
''' Method to call at the beginning of a Delete.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Protected Sub DeleteBegin()
Me.DeletedSucce sfull = True
End Sub
#End Region

#Region "Public Propertys"
''' <name>Propert y SavedSuccesfull </name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique si la classe a été sauvegarder avec succès.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property SavedSuccesfull () As Boolean
Get
Return m_blnSavedSucce sfull
End Get
Set(ByVal value As Boolean)
m_blnSavedSucce sfull = value
End Set
End Property

''' <name>Propert y DeletedSuccesfu ll</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique si la classe a été supprimé avec succès.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property DeletedSuccesfu ll() As Boolean
Get
Return m_blnDeletedSuc cesfull
End Get
Set(ByVal value As Boolean)
m_blnDeletedSuc cesfull = value
End Set
End Property

''' <name>Propert y CatchChanges</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique si le control doit réagir sur des changements ou pas: par
exemple pas pendant qu'on fait le load d'une entité...
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property CatchChanges() As Boolean
Get
Return m_blnCatchChang es
End Get
Set(ByVal value As Boolean)
m_blnCatchChang es = value
Dim clsI As clsBaseClass
For Each clsI In MyBase.Items
clsI.CatchChang es = m_blnCatchChang es
Next
End Set
End Property

''' <name>Propert y ThrowEveryChang esEvent</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Indique qu'un evenement doit être raised à chaque changement, ou
seulement le premier fois...
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property ThrowEveryChang esEvent() As Boolean
Get
Return m_blnThrowEvery ChangesEvent
End Get
Set(ByVal value As Boolean)
m_blnThrowEvery ChangesEvent = value
End Set
End Property

'<System.Compon entModel.Defaul tValue(False)> _
Public Event HasChangesEvent As EventHandler(Of HasChangesEvent Args)
''' <name>Propert y HasChanges</name>
''' <returns>Boolea n</returns>
''' <summary>
''' True s'il y a des changements qui se sont passés aux propertys de
la classe.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property HasChanges() As Boolean
Get
Return m_blnHasChanges
End Get
Set(ByVal value As Boolean)
m_blnHasChanges = value
End Set
End Property

''' <name>Propert y EntiteName</name>
''' <returns>String </returns>
''' <summary>
''' Le nom de l'entité de la classe.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property EntiteName() As String
Get
Return m_strEntiteName
End Get
Set(ByVal value As String)
m_strEntiteName = value
End Set
End Property

''' <name>Propert y EntiteCe</name>
''' <returns>String </returns>
''' <summary>
''' CET adresse, CE fournisseur, ...
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Property EntiteCe() As String
Get
Return m_strEntiteCe
End Get
Set(ByVal value As String)
m_strEntiteCe = value
End Set
End Property

#End Region

#Region "Base Collection Methods"
''' <name>Functio n TestCloseCollec tion</name>
''' <returns>Intege r</returns>
''' <summary>
''' This Methode tests for unsaved changes when CatchChanges is True,
and ask to save unchanged changes.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Function TestCloseCollec tion() As Integer
If Me.m_blnCatchCh anges And Me.m_blnHasChan ges Then
Dim intA As Integer
intA = MessageBox.Show ("Vous avez fait des changements depuis
le dernier sauvegarde." & vbCrLf & "Est-ce que vous voulez les
sauvegarder?", "Sauvegarde r changements?", MessageBoxButto ns.YesNoCancel,
MessageBoxIcon. Warning)

If intA = vbYes Then
'raise event to save the changes
'RaiseEvent Click_Save()
If Me.Save() Then
'if succesfully saved: class can be
disposed/finalized...
Return vbYes
Else
'if not: don't close it...
Return vbCancel
End If
ElseIf intA = vbNo Then
'if they don't want to save the changes: disable the
changes-handler
Me.CatchChanges = False
Return intA
Else
Return intA
End If
Else
Return vbYes
End If
End Function

''' <name>Functio n Save</name>
''' <returns>Boolea n</returns>
''' <summary>
''' ' Update les changements ou insert les dans la base de données pour
tout les objets dans la collection.
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Function Save() As Boolean
Try
Me.SaveBegin()
Dim clsI As clsBaseClass
For Each clsI In MyBase.Items
If Not clsI.Save() Then SavedSuccesfull = False
Next
Catch ex As Exception
'ErrorMessage(e x)
SavedSuccesfull = False
Throw ex
End Try

Me.SaveEnd()
Return SavedSuccesfull
End Function

''' <name>Functio n Delete</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Supprime tout les éléments dans la liste
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Function Delete() As Boolean
Try
Me.DeleteBegin( )
Dim clsI As clsBaseClass
For Each clsI In MyBase.Items
If Not clsI.Delete Then
Me.DeletedSucce sfull = False
Return Me.DeletedSucce sfull
Exit Function
End If
Next

'remove them all
Me.Clear()
Catch ex As Exception
'ErrorMessage(e x)
Me.DeletedSucce sfull = False
Throw ex
End Try

Return Me.DeletedSucce sfull
End Function

''' <name>Functio n Delete</name>
''' <returns>Boolea n</returns>
''' <summary>
''' Deletes a specified Object in the List
''' </summary>
''' <param name="item">ByV al item As T: The item that must be
deleted</param>
''' <history>
''' PCO Created
''' </history>
Public Function Delete(ByVal item As T) As Boolean
Try
Me.DeleteBegin( )
If Not item.Delete Then Me.DeletedSucce sfull = False
Me.Remove(item)
Catch ex As Exception
'ErrorMessage(e x)
Me.DeletedSucce sfull = False
Throw ex
End Try

Return Me.DeletedSucce sfull
End Function

''' <name>Sub SetCollectionTo UnchangedState</name>
''' <summary>
''' Methode qui remets le HasChanges = False et CatchChanges = True
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public Sub SetCollectionTo UnchangedState( )
'reset it
CatchChanges = True
HasChanges = False
End Sub

Private Sub OnObjectInListC hangedHandler(B yVal sender As Object, ByVal
e As HasChangesEvent Args)
'always...
''regarde si on n'as pas déjà fait...
''If (Not m_blnHasChanges ) Then 'il y a une valeur qui est changé!
''ok, il y a une valeur changé
HasChanges = True
RaiseEvent HasChangesEvent (sender, e)
''End If
End Sub

Private Sub OnObjectInListS electedChangedH andler(ByVal sender As
Object, ByVal e As HasChangesEvent Args)
'always...
RaiseEvent HasChangesSelec tedEvent(sender , e)
End Sub

Public Event HasChangesSelec tedEvent As EventHandler(Of
HasChangesEvent Args)

''' <name>ReadOnl y Property SelectedCount() </name>
''' <returns>Intege r</returns>
''' <summary>
''' Property qui retourne le nombre d'Items dans la collection qui a le
property Selected = True
''' </summary>
''' <history>
''' PCO Created
''' </history>
Public ReadOnly Property SelectedCount() As Integer
Get
Dim clsB As clsBaseClass
Dim intC As Integer = 0
For Each clsB In MyBase.Items
If clsB.Selected Then
intC += 1
End If
Next
Return intC
End Get
End Property
#End Region

#Region "List Methods"
Public Shadows Sub Add(ByVal item As T)
item.SetClassTo UnchangedState( )
AddHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
AddHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.Add(item )
End Sub

Public Shadows Sub Insert(ByVal index As Integer, ByVal item As T)
item.SetClassTo UnchangedState( )
AddHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
AddHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.Insert(i ndex, item)
End Sub

Public Shadows Sub Clear()
For Each item As clsBaseClass In Me
RemoveHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
RemoveHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
Next
MyBase.Clear()
End Sub

Public Shadows Function Remove(ByVal item As T) As Boolean
RemoveHandler item.HasChanges Event, AddressOf
OnObjectInListC hangedHandler
RemoveHandler item.SelectedCh anged, AddressOf
OnObjectInListS electedChangedH andler
Return MyBase.Remove(i tem)
End Function

Public Shadows Sub RemoveAt(ByVal index As Integer)
RemoveHandler MyBase.Item(ind ex).HasChangesE vent, AddressOf
OnObjectInListC hangedHandler
RemoveHandler MyBase.Item(ind ex).SelectedCha nged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.RemoveAt (index)
End Sub

'very important, otherwise it will return objects of clsBaseClass, and
not object of T...
Default Public Shadows Property Item(ByVal index As Integer) As T
Get
Return MyBase.Item(ind ex)
End Get
Set(ByVal value As T)
AddHandler value.HasChange sEvent, AddressOf
OnObjectInListC hangedHandler
AddHandler value.SelectedC hanged, AddressOf
OnObjectInListS electedChangedH andler
MyBase.Item(ind ex) = value
End Set
End Property

#End Region

#Region "Searching"
Protected Overrides ReadOnly Property SupportsSearchi ngCore() As
Boolean
Get
Return True
End Get
End Property

' Item property descriptor collection cache
Dim pdc As PropertyDescrip torCollection = Nothing

Protected Overrides Function FindCore(ByVal [property] As
PropertyDescrip tor, ByVal key As Object) As Integer
' Specify search columns
If ([property] Is Nothing) Then
Return -1
End If

' Get list to search
Dim items As List(Of T) = Me.Items
' Traverse list for value
For Each item As T In items
' Test column search value
Dim value As String = CStr([property].GetValue(item) )
'If value is the search value, return the
' index of the data item
If (CStr(key) = value) Then
Return IndexOf(item)
End If
Next item
Return -1
End Function

'ByVal [property] As PropertyDescrip tor, ByVal key As Object
Public Function FindItems(ByVal ColumnName As String, ByVal ColumnValue
As Object) As clsBaseList(Of T)
Dim lst As New clsBaseList(Of T)
Dim properties As PropertyDescrip torCollection
Dim myProperty As PropertyDescrip tor

' Specify search columns
If (ColumnName Is Nothing) Then
Return Nothing
End If

' Get list to search
Dim items As List(Of T) = Me.Items
' Traverse list for value
For Each item As T In items
properties = TypeDescriptor. GetProperties(i tem.GetType)
myProperty = properties.Find (ColumnName, False)
' Test column search value
Dim value As String = CStr(myProperty .GetValue(item) )
'If value is the search value, return the
' index of the data item
If (CStr(ColumnVal ue) = value) Then
lst.Add(item)
End If
Next item
Return lst
End Function

Public Function FindItem(ByVal ColumnName As String, ByVal ColumnValue
As Object) As T
Dim properties As PropertyDescrip torCollection =
TypeDescriptor. GetProperties(M e.Items(0).GetT ype)
Dim myProperty As PropertyDescrip tor = properties.Find (ColumnName,
False)
Dim i As Integer = FindCore(myProp erty, ColumnValue)
If i = -1 Then
Return Nothing
Else
Return Me.Item(i)
End If
End Function

Public Function SumItems(ByVal ColumnName As String) As Decimal
Dim properties As PropertyDescrip torCollection
Dim myProperty As PropertyDescrip tor

' Specify search columns
If (ColumnName Is Nothing) Then
Return Nothing
End If

' Get list to search
Dim items As List(Of T) = Me.Items
' Traverse list for value
Dim decSum As Decimal = 0
For Each item As T In items
properties = TypeDescriptor. GetProperties(i tem.GetType)
myProperty = properties.Find (ColumnName, False)
'Dim value As String = CStr(myProperty .GetValue(item) )
decSum += CSng(myProperty .GetValue(item) )
Next item
Return decSum
End Function

#End Region

End Class

Public Class clsListComparer
Implements IComparer

Private m_SortList As ListSortDescrip tionCollection

Public Sub New(ByVal SortProperty As PropertyDescrip tor, ByVal
direction As ListSortDirecti on)
'Create a new list every time
m_SortList = New ListSortDescrip tionCollection( New
ListSortDescrip tion() {New ListSortDescrip tion(SortProper ty, direction)})
End Sub

Public Sub New(ByVal SortList As ListSortDescrip tionCollection)
m_SortList = SortList
End Sub

Private Function CompareSinglePr operty(ByVal x As clsBaseClass, ByVal y
As clsBaseClass, ByVal prop As PropertyDescrip tor, ByVal direction As
ListSortDirecti on) As Integer
Dim result As Integer = 0
Dim directionModifi er As Integer
If (direction = ListSortDirecti on.Ascending) Then
directionModifi er = 1
Else
directionModifi er = -1
End If
If (x Is Nothing) Then
result = -1 * directionModifi er
ElseIf (y Is Nothing) Then
result = 1 * directionModifi er
ElseIf (prop.GetValue( x) < prop.GetValue(y )) Then
result = -1 * directionModifi er
ElseIf (prop.GetValue( x) > prop.GetValue(y )) Then
result = 1 * directionModifi er
Else
result = 0
End If
Return result
End Function

Private Function Compare(ByVal x As Object, ByVal y As Object) As
Integer _
Implements System.Collecti ons.IComparer.C ompare
Dim idx As Integer
Dim result As Integer
If (Not TypeOf x Is clsBaseClass) Then
Throw New ArgumentExcepti on("Unexpected Argument. Arguments
must be of Type ", "x")
End If
If (Not TypeOf y Is clsBaseClass) Then
Throw New ArgumentExcepti on("Unexpected Argument. Arguments
must be of Type ", "y")
End If
For idx = 0 To m_SortList.Coun t - 1
result = CompareSinglePr operty(x, y,
m_SortList(idx) .PropertyDescri ptor, m_SortList(idx) .SortDirection)
If (result <> 0) Then
Exit For
End If
Next
Return result
End Function
End Class


Mar 23 '06 #3
"Arthur Dent" <hi************ *********@yahoo .com> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
I could do that, but the thing is that that defeats the point of OO. I was
trying to take advantage of the generic collection as a base so i wouldnt
have to reinvent the wheel..... theres a lot of code involved in coding
collection classes.


Well, that's exactly what I did: it is taken all the advantages of the
generic classes, it was a bit more difficult, but really worth it (I like
generics): as you can see: "Public Class clsBaseList(Of T As clsBaseClass)".
So I didn't reinvent the wheel here I think :)

Althoug, in my particular case all my objects inherit from clsBaseClass,
which handles a lot of common functionality for my objects.
Mar 24 '06 #4
Arthur,
In addition to the other comments:
Remember that Collection(Of T) is simply a wrapper for an object that
implements IList(Of T). This wrapped IList(Of T) does all the "heavy
lifting" the Collection(Of T) simply delegates to the wrapped IList(Of T).
<sidenote>Rea d Collection(Of T) uses the Strategy Pattern. The IList(Of T)
is the strategy it uses to implement the list itself, by default its uses an
array like structure for the strategy (the List(Of T), you can easily
replace the strategy with a LinkedList or a Binary tree, see below for
details on replacing the strategy...</sidenote>

You can use Collection(Of T).Items to get at the wrapped IList(Of T).

By default Collection(Of T) uses a List(Of T) as the wrapped IList(Of T),
List(Of T) has a Sort method (plus a plethora of other methods).
Collection(Of T).Items is how you get at the wrapped IList(Of T). In other
words casting Collection(Of T).Items to List(Of T) should allow you to call
its Sort method.

Something like:

Public Class Person
Implements IComparable(Of Person)

...

Public Function CompareTo(ByVal other As Person) As Integer
Implements System.ICompara ble(Of Person).Compare To
...
End Function

End Class

Public Class PersonCollectio n
Inherits ObjectModel.Col lection(Of Person)

Public Sub Sort()
DirectCast(Item s, List(Of Person)).Sort()
End Sub

End Class

I would consider introducing a new generic collection base that incorporates
this sorting:

Public Class CollectionBase( Of T)
Inherits ObjectModel.Col lection(Of T)

Public Sub Sort()
DirectCast(Item s, List(Of T)).Sort()
End Sub

Public Sub Sort(ByVal comparer As IComparer(Of T))
DirectCast(Item s, List(Of T)).Sort(compar er)
End Sub

Public Sub Sort(ByVal index As Integer, ByVal count As Integer,
ByVal comparer As IComparer(Of T))
DirectCast(Item s, List(Of T)).Sort(index, count, comparer)
End Sub

Public Sub Sort(ByVal comparison As Comparison(Of T))
DirectCast(Item s, List(Of T)).Sort(compar ison)
End Sub

End Class

Then PersonCollectio n would be based on this new base:

Public Class PersonCollectio n
Inherits CollectionBase( Of Person)

End Class
NOTE: The above may fail if you call Collection(Of T).New(IList(Of T))
passing in a something other then List(Of T). For example:

Public Class PersonCollectio n
Inherits ObjectModel.Col lection(Of Person)

' use a linked list strategy
Public Sub New()
MyBase.New(New LinkedList(Of Person))
End Sub

' use an array strategy
Public Sub New()
MyBase.New(New Person(100-1) {}) ' base it on an 100 element
array
End Sub

' use some other generic collection strategy
' where SpecializedColl ection implements IList(Of T)
Public Sub New()
MyBase.New(New SpecializedColl ection(Of Person))
End Sub

End Class

The Frameworks LinkedList(Of T) does not implement IList(Of T) although it
is easy to add. The array does work (as the wrapped list), giving you a
fixed sized collection that you cannot add or remove elements from (you can
only change existing entries)...

I have not yet posted my sample LinkedList(Of T) that implements IList(Of T)
to my web site...

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Arthur Dent" <hi************ *********@yahoo .com> wrote in message
news:eA******** ******@TK2MSFTN GP11.phx.gbl...
| How do you sort a generic collection derived from
| System.Collecti ons.ObjectModel .Collection?
|
| Thanks in advance,
| - Arthur Dent
|
|
Mar 24 '06 #5
Thank you, that was exactly what i was looking for, getting at the inner
list object to be able to use its methods.
Cheers!
"Jay B. Harlow [MVP - Outlook]" <Ja************ @tsbradley.net> wrote in
message news:eU******** ******@tk2msftn gp13.phx.gbl...
Arthur,
In addition to the other comments:
Remember that Collection(Of T) is simply a wrapper for an object that
implements IList(Of T). This wrapped IList(Of T) does all the "heavy
lifting" the Collection(Of T) simply delegates to the wrapped IList(Of T).
<sidenote>Rea d Collection(Of T) uses the Strategy Pattern. The IList(Of
T)
is the strategy it uses to implement the list itself, by default its uses
an
array like structure for the strategy (the List(Of T), you can easily
replace the strategy with a LinkedList or a Binary tree, see below for
details on replacing the strategy...</sidenote>

You can use Collection(Of T).Items to get at the wrapped IList(Of T).

By default Collection(Of T) uses a List(Of T) as the wrapped IList(Of T),
List(Of T) has a Sort method (plus a plethora of other methods).
Collection(Of T).Items is how you get at the wrapped IList(Of T). In other
words casting Collection(Of T).Items to List(Of T) should allow you to
call
its Sort method.

Something like:

Public Class Person
Implements IComparable(Of Person)

...

Public Function CompareTo(ByVal other As Person) As Integer
Implements System.ICompara ble(Of Person).Compare To
...
End Function

End Class

Public Class PersonCollectio n
Inherits ObjectModel.Col lection(Of Person)

Public Sub Sort()
DirectCast(Item s, List(Of Person)).Sort()
End Sub

End Class

I would consider introducing a new generic collection base that
incorporates
this sorting:

Public Class CollectionBase( Of T)
Inherits ObjectModel.Col lection(Of T)

Public Sub Sort()
DirectCast(Item s, List(Of T)).Sort()
End Sub

Public Sub Sort(ByVal comparer As IComparer(Of T))
DirectCast(Item s, List(Of T)).Sort(compar er)
End Sub

Public Sub Sort(ByVal index As Integer, ByVal count As Integer,
ByVal comparer As IComparer(Of T))
DirectCast(Item s, List(Of T)).Sort(index, count, comparer)
End Sub

Public Sub Sort(ByVal comparison As Comparison(Of T))
DirectCast(Item s, List(Of T)).Sort(compar ison)
End Sub

End Class

Then PersonCollectio n would be based on this new base:

Public Class PersonCollectio n
Inherits CollectionBase( Of Person)

End Class
NOTE: The above may fail if you call Collection(Of T).New(IList(Of T))
passing in a something other then List(Of T). For example:

Public Class PersonCollectio n
Inherits ObjectModel.Col lection(Of Person)

' use a linked list strategy
Public Sub New()
MyBase.New(New LinkedList(Of Person))
End Sub

' use an array strategy
Public Sub New()
MyBase.New(New Person(100-1) {}) ' base it on an 100 element
array
End Sub

' use some other generic collection strategy
' where SpecializedColl ection implements IList(Of T)
Public Sub New()
MyBase.New(New SpecializedColl ection(Of Person))
End Sub

End Class

The Frameworks LinkedList(Of T) does not implement IList(Of T) although it
is easy to add. The array does work (as the wrapped list), giving you a
fixed sized collection that you cannot add or remove elements from (you
can
only change existing entries)...

I have not yet posted my sample LinkedList(Of T) that implements IList(Of
T)
to my web site...

--
Hope this helps
Jay [MVP - Outlook]
.NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Arthur Dent" <hi************ *********@yahoo .com> wrote in message
news:eA******** ******@TK2MSFTN GP11.phx.gbl...
| How do you sort a generic collection derived from
| System.Collecti ons.ObjectModel .Collection?
|
| Thanks in advance,
| - Arthur Dent
|
|

Mar 25 '06 #6
Arthur,

Thinking about it, it might be better to ensure that you have a wrapped
List(Of T) verses some other IList(Of T) collection... Especially when
introducing a new generic base class...

| > Public Class CollectionBase( Of T)
| > Inherits ObjectModel.Col lection(Of T)
| >
Public Sub New()
MyBase.New()
End Sub

Public Sub New(list As IList(Of T))
MyBase.New(list )
End Sub

| > Public Sub Sort()
Dim list As List(Of T) = TryCast(Items, List(Of T))
If list Is Nothing Then Throw New NotSupportedExc eption()
list.Sort()
| > End Sub
| >

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net
"Arthur Dent" <hi************ *********@yahoo .com> wrote in message
news:%2******** **********@TK2M SFTNGP10.phx.gb l...
| Thank you, that was exactly what i was looking for, getting at the inner
| list object to be able to use its methods.
| Cheers!
|
|
| "Jay B. Harlow [MVP - Outlook]" <Ja************ @tsbradley.net> wrote in
| message news:eU******** ******@tk2msftn gp13.phx.gbl...
| > Arthur,
| > In addition to the other comments:
| >
| >
| > Remember that Collection(Of T) is simply a wrapper for an object that
| > implements IList(Of T). This wrapped IList(Of T) does all the "heavy
| > lifting" the Collection(Of T) simply delegates to the wrapped IList(Of
T).
| > <sidenote>Rea d Collection(Of T) uses the Strategy Pattern. The IList(Of
| > T)
| > is the strategy it uses to implement the list itself, by default its
uses
| > an
| > array like structure for the strategy (the List(Of T), you can easily
| > replace the strategy with a LinkedList or a Binary tree, see below for
| > details on replacing the strategy...</sidenote>
| >
| > You can use Collection(Of T).Items to get at the wrapped IList(Of T).
| >
| > By default Collection(Of T) uses a List(Of T) as the wrapped IList(Of
T),
| > List(Of T) has a Sort method (plus a plethora of other methods).
| > Collection(Of T).Items is how you get at the wrapped IList(Of T). In
other
| > words casting Collection(Of T).Items to List(Of T) should allow you to
| > call
| > its Sort method.
| >
| > Something like:
| >
| > Public Class Person
| > Implements IComparable(Of Person)
| >
| > ...
| >
| > Public Function CompareTo(ByVal other As Person) As Integer
| > Implements System.ICompara ble(Of Person).Compare To
| > ...
| > End Function
| >
| > End Class
| >
| > Public Class PersonCollectio n
| > Inherits ObjectModel.Col lection(Of Person)
| >
| > Public Sub Sort()
| > DirectCast(Item s, List(Of Person)).Sort()
| > End Sub
| >
| > End Class
| >
| > I would consider introducing a new generic collection base that
| > incorporates
| > this sorting:
| >
| > Public Class CollectionBase( Of T)
| > Inherits ObjectModel.Col lection(Of T)
| >
| > Public Sub Sort()
| > DirectCast(Item s, List(Of T)).Sort()
| > End Sub
| >
| > Public Sub Sort(ByVal comparer As IComparer(Of T))
| > DirectCast(Item s, List(Of T)).Sort(compar er)
| > End Sub
| >
| > Public Sub Sort(ByVal index As Integer, ByVal count As Integer,
| > ByVal comparer As IComparer(Of T))
| > DirectCast(Item s, List(Of T)).Sort(index, count, comparer)
| > End Sub
| >
| > Public Sub Sort(ByVal comparison As Comparison(Of T))
| > DirectCast(Item s, List(Of T)).Sort(compar ison)
| > End Sub
| >
| > End Class
| >
| > Then PersonCollectio n would be based on this new base:
| >
| > Public Class PersonCollectio n
| > Inherits CollectionBase( Of Person)
| >
| > End Class
| >
| >
| > NOTE: The above may fail if you call Collection(Of T).New(IList(Of T))
| > passing in a something other then List(Of T). For example:
| >
| > Public Class PersonCollectio n
| > Inherits ObjectModel.Col lection(Of Person)
| >
| > ' use a linked list strategy
| > Public Sub New()
| > MyBase.New(New LinkedList(Of Person))
| > End Sub
| >
| > ' use an array strategy
| > Public Sub New()
| > MyBase.New(New Person(100-1) {}) ' base it on an 100 element
| > array
| > End Sub
| >
| > ' use some other generic collection strategy
| > ' where SpecializedColl ection implements IList(Of T)
| > Public Sub New()
| > MyBase.New(New SpecializedColl ection(Of Person))
| > End Sub
| >
| > End Class
| >
| > The Frameworks LinkedList(Of T) does not implement IList(Of T) although
it
| > is easy to add. The array does work (as the wrapped list), giving you a
| > fixed sized collection that you cannot add or remove elements from (you
| > can
| > only change existing entries)...
| >
| > I have not yet posted my sample LinkedList(Of T) that implements
IList(Of
| > T)
| > to my web site...
| >
| > --
| > Hope this helps
| > Jay [MVP - Outlook]
| > .NET Application Architect, Enthusiast, & Evangelist
| > T.S. Bradley - http://www.tsbradley.net
| >
| >
| > "Arthur Dent" <hi************ *********@yahoo .com> wrote in message
| > news:eA******** ******@TK2MSFTN GP11.phx.gbl...
| > | How do you sort a generic collection derived from
| > | System.Collecti ons.ObjectModel .Collection?
| > |
| > | Thanks in advance,
| > | - Arthur Dent
| > |
| > |
| >
| >
|
|
Mar 25 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
2889
by: Howard Swope | last post by:
Could someone help explain thread safety issues in the System.Collections classes? The documentation states: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Thread Safety Public static (Shared in Visual Basic) members of this type are safe for multithreaded operations. Instance members are not guaranteed to be thread-safe. A SortedList can support multiple readers concurrently,...
6
5939
by: Paul Delhanty | last post by:
Hi, I am converting an existing native C++ program making heavy use of STL to C#2.0 with STL usage replaced by the new generic collections. The conversion has gone well to the point where I am replacing an STL map instance by a System.Collections.Generic.SortedDictionary instance. In need the collection to be ordered, and to have o(log(n)) look up - that is fine so far SortedDictionary.TryGetValue does the job. I also need the...
6
2730
by: Bern McCarty | last post by:
I'm trying to use the VS 2005 March Tech Preview and am trying to adjust some MC++ to the new C++/CLI syntax. I got a little hung up when I encountered the below error. Certainly my 'Bentley::Mstn::Element' type derives ultimately from System::Object. It is a ref class. And upcasting is always implicit right? So I don't understand why I'm getting this error. It's happening on my get method: property Bentley::Mstn::Element^ Item {...
4
8182
by: nhmark64 | last post by:
Hi, Does System.Collections.Generic.Queue not have a Synchronized method because it is already in effect synchronized, or is the Synchronized functionality missing from System.Collections.Generic.Queue? Putting it another way can I safely replace a System.Collections.Queue.Synchronized(myUnSynchronizedQueue) with a System.Collections.Generic.Queue while porting a working 2003 project? Thanks,
2
2061
by: newscorrespondent | last post by:
I have a list declared: public System.Collections.Generic.SortedList<int, System.Collections.Generic.List<MTGTracer ActiveList = new SortedList<int,List<MTGTracer>>(); The key is an integer and the value is a list of MTGTracer. The documentation states:
2
2170
by: GoCoogs | last post by:
I'm trying to count how many items are in a dynamic collection. This is the code I have so far. *** Begin Code *** Public Class Rule Private _rulevars As RuleVarsCollection Private _rulename As String Public Property Name() As String Get
1
1896
by: JackPot | last post by:
The question being like where is System.Collections.ObjectModel.Collection? I'm using Roeder's Reflector and come across the following: private Collection<int>channelSkipHours; When I click on Collection I get a dialog stating "The member is not loaded or may be hidden due to your website settings." So I try to use Reflector to peruse the CommonLanguageRuntimeLibrary and navigate through System.Collections but there is not...
3
16156
by: Marco Shaw | last post by:
I've got some C# code to create a custom PowerShell cmdlet with these statements: .... using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; .... My compile fails using csc.exe:
3
3491
by: Monty | last post by:
I have a bit of common code that I've been using for a while to return a dictionary collection of dataobjects. I've made some changes to it and other areas of the project, and suddenly I am getting this error (below) whenever I call it. My changes were small and I don't think they would have caused anything like this. Error message: Error: Method not found: 'System.Collections.Generic.Dictionary`2<System.String,...
0
9110
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8971
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8812
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7650
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5825
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4332
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4568
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2249
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1970
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.