Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum. Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

Sujet : Trier Les Entiers d'une Listview [ Divers / Débutants ] (naim1970)

lundi 21 juillet 2008 à 14:01:54 | Trier Les Entiers d'une Listview

naim1970

Bonjour,

 

Un petit blèm pour trier les entiers (Integers) avec la class Compare dans Listview.

 

1

10

11

13

2

23

24

25

3
30 

Le code que j'ai trouvé sur msdn trie les strings et dates.

Comme faire pour trier les entiers ?

 

Exemple

1

2

310

11

13

23

24

25

30
...
 

Voici le Code

 

Public Function Compare(ByVal x AsObject, ByVal y AsObject) AsIntegerImplements System.Collections.IComparer.Compare

            Try

              

                ' Parse the two objects passed as a parameter as a DateTime.

                Dim firstDate As System.DateTime = DateTime.Parse(CType(x, ListViewItem).SubItems(col).Text)

                Dim secondDate As System.DateTime = DateTime.Parse(CType(y, ListViewItem).SubItems(col).Text)

                ' Compare the two dates.

                returnVal = DateTime.Compare(firstDate, secondDate)

                ' If neither compared object has a valid date format,

                ' compare as a string.

            Catch

                ' Compare the two items as a string.

                returnVal = [String].Compare(CType(x, _

                                  ListViewItem).SubItems(col).Text, CType(y, ListViewItem).SubItems(col).Text)

            End Try

 

            ' Determine whether the sort order is descending.

             If order = SortOrder.Descending Then

                ' Invert the value returned by String.Compare.

                returnVal *= -1

            End If

            Return returnVal

 

        End Function

    End Class

 

 

Merci pour votre aide.

 

 



naim1970

lundi 21 juillet 2008 à 14:21:18 | Re : Trier Les Entiers d'une Listview

Renfield

Administrateur CodeS-SourceS
Réponse acceptée !
tu effectue le tri que tu souhaites....
les données du listview sont des String.

pour trier des dates, on tentes de les convertir en date :

Dim firstDate As System.DateTime = DateTime.Parse(CType(x, ListViewItem).SubItems(col).Text)

pour un tri numérique, c'est exactement identique...

Dim firstInt As System.Integer = Integer.Parse(CType(x, ListViewItem).SubItems(col).Text)


le tout étant d'effectuer ta comparaison, et de renvoyer -1, 0 ou 1 ...



lundi 21 juillet 2008 à 17:49:27 | Re : Trier Les Entiers d'une Listview

gillardg

Imports

System.Globalization

Public

Class NaturalComparer

Implements IComparer( Of String )

Implements IComparer

Private mParser1 As StringParser

Private mParser2 As StringParser

Private mNaturalComparerOptions As NaturalComparerOptions

Private Enum TokenType

[Nothing]

Numerical

[String]

End Enum

Private Class StringParser

Private mTokenType As TokenType

Private mStringValue As String

Private mNumericalValue As Decimal

Private mIdx As Integer

Private mSource As String

Private mLen As Integer

Private mCurChar As Char

Private mNaturalComparer As NaturalComparer

Sub New ( ByVal naturalComparer As NaturalComparer)

mNaturalComparer = naturalComparer

End Sub

Public Sub Init( ByVal source As String )

If source Is Nothing Then source = String .Empty

mSource = source

mLen = source.Length

mIdx = -1

mNumericalValue = 0

NextChar()

NextToken()

End Sub

Public ReadOnly Property TokenType() As TokenType

Get

Return mTokenType

End Get

End Property

Public ReadOnly Property NumericalValue() As Decimal

Get

If mTokenType = NaturalComparer.TokenType.Numerical Then

Return mNumericalValue

Else

Throw New NaturalComparerException( "Internal Error: NumericalValue called on a non numerical value." )

End If

End Get

End Property

Public ReadOnly Property StringValue() As String

Get

Return mStringValue

End Get

End Property

Public Sub NextToken()

Do

'CharUnicodeInfo.GetUnicodeCategory

If mCurChar = Nothing Then

mTokenType = NaturalComparer.TokenType.Nothing

mStringValue =

Nothing

Exit Sub

ElseIf Char .IsDigit(mCurChar) Then

ParseNumericalValue()

Exit Sub

ElseIf Char .IsLetter(mCurChar) Then

ParseString()

Exit Sub

Else

'ignore this character and loop some more

NextChar()

End If

Loop

End Sub

Private Sub NextChar()

mIdx += 1

If mIdx >= mLen Then

mCurChar =

Nothing

Else

mCurChar = mSource(mIdx)

End If

End Sub

Private Sub ParseNumericalValue()

Dim start As Integer = mIdx

Dim NumberDecimalSeparator As Char = NumberFormatInfo.CurrentInfo.NumberDecimalSeparator(0)

Dim NumberGroupSeparator As Char = NumberFormatInfo.CurrentInfo.NumberGroupSeparator(0)

Do

NextChar()

If mCurChar = NumberDecimalSeparator Then

' parse digits after the Decimal Separator

Do

NextChar()

If Not Char .IsDigit(mCurChar) AndAlso mCurChar <> NumberGroupSeparator Then Exit Do

Loop

Exit Do

Else

If Not Char .IsDigit(mCurChar) AndAlso mCurChar <> NumberGroupSeparator Then Exit Do

End If

Loop

mStringValue = mSource.Substring(start, mIdx - start)

If Decimal .TryParse(mStringValue, mNumericalValue) Then

mTokenType = NaturalComparer.TokenType.Numerical

Else

' We probably have a too long value

mTokenType = NaturalComparer.TokenType.String

End If

End Sub

Private Sub ParseString()

Dim start As Integer = mIdx

Dim roman As Boolean = (mNaturalComparer.mNaturalComparerOptions And NaturalComparerOptions.RomanNumbers) <> 0

Dim romanValue As Integer

Dim lastRoman As Integer = Integer .MaxValue

Dim cptLastRoman As Integer

Do

If roman Then

Dim thisRomanValue As Integer = RomanLetterValue(mCurChar)

If thisRomanValue > 0 Then

Dim handled As Boolean = False

If (thisRomanValue = 1 OrElse thisRomanValue = 10 OrElse thisRomanValue = 100) Then

NextChar()

Dim nextRomanValue As Integer = RomanLetterValue(mCurChar)

If nextRomanValue = thisRomanValue * 10 Or nextRomanValue = thisRomanValue * 5 Then

handled =

True

If nextRomanValue <= lastRoman Then

romanValue += nextRomanValue - thisRomanValue

NextChar()

lastRoman = thisRomanValue \ 10

cptLastRoman = 0

Else

roman =

False

End If

End If

Else

NextChar()

End If

If Not handled Then

If thisRomanValue <= lastRoman Then

romanValue += thisRomanValue

If lastRoman = thisRomanValue Then

cptLastRoman += 1

Select Case thisRomanValue

Case 1, 10, 100

If cptLastRoman > 4 Then roman = False

Case 5, 50, 500

If cptLastRoman > 1 Then roman = False

End Select

Else

lastRoman = thisRomanValue

cptLastRoman = 1

End If

Else

roman =

False

End If

End If

Else

roman =

False

End If

Else

NextChar()

End If

If Not Char .IsLetter(mCurChar) Then Exit Do

Loop

mStringValue = mSource.Substring(start, mIdx - start)

If roman Then

mNumericalValue = romanValue

mTokenType = NaturalComparer.TokenType.Numerical

Else

mTokenType = NaturalComparer.TokenType.String

End If

End Sub

End Class

Sub New ( ByVal NaturalComparerOptions As NaturalComparerOptions)

mNaturalComparerOptions = NaturalComparerOptions

mParser1 =

New StringParser( Me )

mParser2 =

New StringParser( Me )

End Sub

Sub New ()

MyClass .New(NaturalComparerOptions.Default)

End Sub

Public Function Compare( ByVal string1 As String , ByVal string2 As String ) As Integer Implements System.Collections.Generic.IComparer( Of String ).Compare

mParser1.Init(string1)

mParser2.Init(string2)

Dim result As Integer

Do

If mParser1.TokenType = TokenType.Numerical And mParser2.TokenType = TokenType.Numerical Then

' both string1 and string2 are numerical

result =

Decimal .Compare(mParser1.NumericalValue, mParser2.NumericalValue)

Else

result =

String .Compare(mParser1.StringValue, mParser2.StringValue)

End If

If result <> 0 Then

Return result

Else

mParser1.NextToken()

mParser2.NextToken()

End If

Loop Until mParser1.TokenType = TokenType.Nothing And mParser2.TokenType = TokenType.Nothing

Return 0 'identical

End Function

Private Shared Function RomanLetterValue( ByVal c As Char ) As Integer

Select Case c

Case "I"c

Return 1

Case "V"c

Return 5

Case "X"c

Return 10

Case "L"c

Return 50

Case "C"c

Return 100

Case "D"c

Return 500

Case "M"c

Return 1000

Case Else

Return 0

End Select

End Function

Public Function RomanValue( ByVal string1 As String ) As Integer

mParser1.Init(string1)

If mParser1.TokenType = TokenType.Numerical Then

Return CInt (mParser1.NumericalValue)

Else

Return 0

End If

End Function

Public Function IComparer_Compare( ByVal x As Object , ByVal y As Object ) As Integer Implements System.Collections.IComparer.Compare

Return Compare( DirectCast (x, String ), DirectCast (x, String ))

End Function

End

Class

<System.Flags()>

Public Enum NaturalComparerOptions

None

RomanNumbers

'DecimalValues <- we could put this as an option

'IgnoreSpaces <- we could put this as an option

'IgnorePunctuation <- we could put this as an option

[Default] = None

End

Enum

Public

Class NaturalComparerException

Inherits Exception

Sub New ( ByVal msg As String )

MyBase .New(msg)

End Sub

End

Class

Au contraire des chasseurs qui ne sont pas des lapins, les pollueurs, eux, sont des ordures

/B>



Cette discussion est classé dans : entiers, compare, trier, datetime, ctype


Répondre à ce message

Sujets en rapport avec ce message

Comment trier un fichier ASCII ?? [ par Cesar ] Salut,Je voudrai trier un fichier ecrit par WRITE #1,xx,xx,xx,xx,xx,etc...Il contiens a peux pres 500 ligne sur 10 colonnes.Sinon, le moyen de trier u Trie dans un contrôle ListView [ par Nicolas ] J'ai petit problème avec le contrôle ListView, je parvient trés bien à trier les différentes colonnes au moyen de la proprieté "SortOrder, mais je n'a comment trier un tableau? [ par david ] Existe -t'il une fonction (SORT???) pour classer par ordre croissant ou décroissant les éléments d'un tableau à 1 dimensionet sinon quel algoritme si Trier les éléments d'une DBCombo [ par thomrico ] Bonjour,J'ai une liste déroulante de type DBCombo qui est relié à une base de données. Donc ma liste est composée des élements enregistrés dans cette aidez-moi! trier des données dans une liste [ par sony22 ] A partir d'un ou plusieurs chiffres tapées dans un textbox(départements)trier dans une colonne les données correspondantes et afficher dans un combobo trier par ordre [ par | - BLAFARD - | ] N'y aurait y il pas une gentille personne quipourrai comment faire un alghoritme de tri rapide trier par ordre croissant ou décroissant [ par | - BLAFARD - | ] option base 1g une variable var1(6)j'aimerai ranger ca par ordre décroissant dans un varvar2(6) style :var1(1)=5 var1(2)=2 var1(3)=6 var1(4) Prog pour trier les TabIndex dans les prog VB [ par llimz ] Salut !Je voudrais savoir s'il existe un programme qui trie l'ordre des tabulations sur les contrôles d'une feuille. MerciJimmy Trier une colonne contenant des nombres (listview) [ par Krazitchek ] Comment trier une colonne contenant des nombres dans une listview en report sans que le chiffre 10 (entre autre) se place avant le 2, par exemple, 1,1 Comment trier une feuille AVEC ses noms de cellules? [ par Denis ] Est-ce possible de trier une feuille AVEC ses noms de cellules?merci d'avance


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

Logiciels à télécharger sur le même thème :

Comparez les prix Nouvelle version


LG KP501

Entre 9€ et 159€


Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,296 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.