
![]() |
Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
|
ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
[34.229.63.28] |
![]() |
|
Страницы: (2) [1] 2 все ( Перейти к последнему сообщению ) |
![]() |
|
|
Мне надо отсортированить TStringList. Нашла в DRKB3 Вот как:
![]() ![]() MyList := TStringList.Create; MyList.Sorted := False; try begin for I := 1 to (CountItem - 1) do MyList.Add(GenStrGrid.Rows[I].Strings[ThatCol] + TheSeparator + GenStrGrid.Rows[I].Text); Mylist.Sort; Но тут сортирует по возрастанию. А мне оказалось надо по убыванию. Пожскажите пожалуйста. Может есть какой параметр типа Asc, desc |
Сообщ.
#2
,
|
|
|
![]() ![]() function MySort(List: TStringList; Index1, Index2: Integer): Integer; begin if List[Index1]<List[Index2] then begin Result := 1; Exit; end; if List[Index1]=List[Index2] then Result := 0 else Result := -1; end; ... Mylist.CustomSort(MySort); |
Сообщ.
#3
,
|
|
|
а что такое Index1, Index2?
|
Сообщ.
#4
,
|
|
|
Цитата mopsik @ а что такое Index1, Index2? Метод CustomSort позволяет осуществить порьзовательскую сортировку. В функцию для сортировки передаются индексы строк в TStrings (Index1 и Index2), которые нужно сравнить. Открой справку Delphi. |
Сообщ.
#5
,
|
|
|
Метод Sort объекта класса TStringList по умочанию сортирует во возрастанию.
Цитата Sorts the strings in the list in ascending order. Если посмотреть как это реализовано: ![]() ![]() function StringListCompareStrings(List: TStringList; Index1, Index2: Integer): Integer; begin Result := List.CompareStrings(List.FList^[Index1].FString, List.FList^[Index2].FString); end; procedure TStringList.Sort; begin CustomSort(StringListCompareStrings); end; То можно легко догадаться, что для сортировки по убыванию надо переписать: ![]() ![]() function StringListCompareStringsDesc(List: TStringList; Index1, Index2: Integer): Integer; begin Result := List.CompareStrings(List.FList^[Index2].FString, List.FList^[Index1].FString); end; И уже потом использовать метод CustomSort: ![]() ![]() var Strs: TStringList; begin Strs := TStringList.Create; try Strs.Add(...); ... Strs.CustomSort(StringListCompareStringsDesc); ... finally Strs.Free; end; |
Сообщ.
#6
,
|
|
|
Selya
см. реализацию InternalCompareText. Менее эффективный код в данном случае. |
Сообщ.
#7
,
|
|
|
Товарищи, я делаю, как вы говорите, но у меня на строчке Mylist.CustomSort(mysort)ругается:
![]() ![]() Incompatible types: regular procedure and method pointer |
Сообщ.
#8
,
|
|
|
Цитата mopsik @ Incompatible types: regular procedure and method pointer А ты что, MySort методом класса сделала? |
Сообщ.
#9
,
|
|
|
![]() ![]() unit Unit1; interface uses ...; type ... function MySort(List: TStringList; Index1, Index2: Integer): Integer; stdcall; implementation ... function TForm1.MySort(List: TStringList; Index1, Index2: Integer): Integer;stdcall; begin if List[Index1]<List[Index2] then begin Result := 1; Exit; end; if List[Index1]=List[Index2] then Result := 0 else Result := -1; end; procedure TForm1.SortStringGrid(var GenStrGrid: TStringGrid; ThatCol: Integer); //тут у меня сама процедура создания листа , занесения данных и ........сортировка MyList := TStringList.Create; MyList.Sorted := False; try begin for I := 1 to (CountItem - 1) do MyList.Add(GenStrGrid.Rows[I].Strings[ThatCol] + TheSeparator + GenStrGrid.Rows[I].Text); Mylist.CustomSort(mysort); |
Сообщ.
#10
,
|
|
|
![]() ![]() type TForm1=... ... ... end; [B]function MySort(List: TStringList; Index1, Index2: Integer): Integer;[/B] implementation [B]function MySort(List: TStringList; Index1, Index2: Integer): Integer;[/B] begin if List[Index1]<List[Index2] then begin Result := 1; Exit; end; if List[Index1]=List[Index2] then Result := 0 else Result := -1; end; И никаких stdcall! |
Сообщ.
#11
,
|
|
|
Ой, исправила.....исправила!
Получилось....получилось! ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]() Демо спасибо большое |
Сообщ.
#12
,
|
|
|
[quote=mopsik,1212926208,1981206]А мне оказалось надо по убыванию.[/quote]
Ну в таком случае все гораздо тривиальнее! ![]() [quote=mopsik,1212926208,1981206]for I := 1 to (CountItem - 1) do[/quote] Надо заменить на строку ![]() ![]() for I := (CountItem - 1) downto 1 do[/quote] ЗЫЖ Кстати, индексы начинаяют с нуля... |
Сообщ.
#13
,
|
|
|
[quote=Felan,1212986535,1981559]Строку
Цитата (mopsik @ Вчера, 17:56) for I := 1 to (CountItem - 1) do Надо заменить на строку for I := (CountItem - 1) downto 1 do[/quote] [/quote] ![]() |
Сообщ.
#14
,
|
|
|
Тьфу-ты
![]() ![]() Переклинило меня что-то что это вывод уже. ![]() |
Сообщ.
#15
,
|
|
|
На самом деле - всё гораздо проще.
![]() Идея в том, что если мы имеем хотя бы обычную сортировку, то ничто нам не мешает просто повернуть уже отсортированный лист. ![]() ![]() procedure ReverseList(var List: TStringList); var TmpList: TStringList; I: Integer; begin TmpList := TStringList.Create; for I := List.Count -1 DownTo 0 do TmpList.Append(List[I]); List.Assign(TmpList); TmpList.Free; end; ... procedure TForm1.Button1Click(Sender: TObject); var List: TStringList; begin List := TStringList.Create; List.Append('a'); List.Append('v'); List.Append('e'); List.Append('z'); List.Sort; ReverseList(List); Memo1.Lines.Assign(List); List.Free; end; |