Reputation: 1263
Hi I got next function:
The input ArrayList results is ordered correctly.
The return value returnList is completly unordered.
I think to problem is the HashTable isn't ordered correctly..
Is there a way I can order the Hashtable or should I sort the returnList on someway?
I want to order or sort on a field.
Private Function FilterDepartementenSurveys(ByVal results As ArrayList) As ArrayList
Dim hashTable As New Hashtable(results.Count)
For Each resultaat As DTO.Results.Reporting.FilledInSurvey In results
If Not hashTable.ContainsKey(resultaat.DepartmentCode) Then
hashTable.Add(resultaat.DepartmentCode, New ArrayList)
End If
Dim arraylist As ArrayList = CType(hashTable(resultaat.DepartmentCode), Collections.ArrayList)
arraylist.Add(resultaat)
Next
Dim returnList As New ArrayList
For Each list As ArrayList In hashTable.Values
returnList.Add(list)
Next
Return returnList
End Function
Upvotes: 1
Views: 1190
Reputation: 427
The best way to sort is to use a generic class for sorting which can be used across the application for sorting.
Use the below class which uses Linq and Lamda expression.
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Linq.Expressions
Public Class GenericSorter(Of T)
Public Function Sort(ByVal source As IEnumerable(Of T), _
ByVal sortBy As String, _
ByVal sortDirection As String) As IEnumerable(Of T)
Dim param = Expression.Parameter(GetType(T), "item")
Dim sortExpression = Expression.Lambda(Of Func(Of T, Object))_
(Expression.Convert(Expression.[Property](param, sortBy), _
GetType(Object)), param)
Select Case sortDirection.ToLower
Case "asc"
Return source.AsQueryable().OrderBy(sortExpression)
Case Else
Return source.AsQueryable().OrderByDescending(sortExpression)
End Select
End Function
End Class
For calling this class use the implementation below
Dim gs As New GenericSorter(Of FileDepartmentSurveyData)
SurveyFormatItems = gs.Sort(SurveyFormatItems.AsQueryable, _
sortExpression, sortDirection).ToArray()
http://www.codeproject.com/Articles/37541/Generic-Sorting-with-LINQ-and-Lambda-Expressions
Upvotes: 1
Reputation: 5296
Regular hash tables don't define the order of elements. You probably need a tree structure instead. Retrieval from a tree is O(log N) vs. a hash's O(1). That may or may not be an issue.
Upvotes: 0
Reputation: 499062
From MSDN - HashTable:
Represents a collection of key/value pairs that are organized based on the hash code of the key.
This explains why you don't get the items in the order you expect - they get ordered by the hash of the key.
If you need to preserve ordering, use SortedList
or OrderedDictionary
.
Upvotes: 2
Reputation: 18359
The order in a HashList
is undetermined. Use a TreeMap
instead. See Sort a Map<Key, Value> by values (Java)
Upvotes: 0