StringGridで、カラムの中で、重複する情報がある場合削除する処理を作ってみた
DBのSQL文のdistinct(重複レコードの削除)のような処理
処理は、まず指定カラムで、並び替えを行い
同じカラムの内容がつづいたものを、削除する処理とした
並び替えの処理は、Webにある既存の処理を使った
//http://delfusa.main.jp/delfusafloor/archive/www.nifty.ne.jp_forum_fdelphi/faq/00084.htm
ソート処理
Procedure GridSort(Grid : TStringGrid;SortCol : LongInt);
var
St, St2 : TStringList;
i : Integer;
begin
St := TStringList.Create;
ST.Assign(Grid.Cols[SortCol]);
For i := 1 To Grid.FixedRows Do
St.Delete(0);
For i := Grid.FixedRows To Grid.RowCount - 1 Do
Begin
St2 := TStringList.Create;
St2.Assign(Grid.Rows[i]);
St.Objects[i - Grid.FixedRows] := St2;
End;
St.Sort;
For i := Grid.FixedRows To Grid.RowCount - 1 Do
Begin
Grid.Rows[i].Assign(TStringList(St.Objects[i - Grid.FixedRows]));
TStringList(St.Objects[i - Grid.FixedRows]).Free;
End;
St.Free;
end;
Procedure Distinct(Grid : TStringGrid;CutCol : LongInt);
var
i,j : Integer;
begin
j:=1;
with Grid do
begin
for i:=2 to rowcount-1 do begin
if Cells[CutCol,j]<>Cells[CutCol,i] then begin
// Cells[CutCol,j+1]:=Cells[CutCol,i];
// 行単位で複写
Rows[j+1].Assign(Rows[i]);
j:=j+1;
end
end;
// 重複した行の分に行数を合わせる(不要な行を削除)
rowcount:=j+1;
end;
end;
// テストデータ作成
procedure TForm1.Button1Click(Sender: TObject);
begin
with StringGrid1 do
RowCount:=6;
Cells[1,1]:='abc';
Cells[1,2]:='abc-2';
Cells[1,3]:='abc-1';
Cells[1,4]:='abc-2';
Cells[1,5]:='abc-3';
Cells[2,1]:='1';
Cells[2,2]:='2';
Cells[2,3]:='3';
Cells[2,4]:='4';
Cells[2,5]:='5';
end;
end;
// 動作テスト
procedure TForm1.Button2Click(Sender: TObject);
begin
GridSort(StringGrid1, 1); //1カラム目でソート
Distinct(StringGrid1, 1); //1カラム目で重複削除
end;