带条件的订单清单选择运行时 [英] order List with criteria choose to runtime
问题描述
如果我有一个具有更多字段的泛型列表,例如:
if i have a generics list with more field for example:
PMyList = record
Field1, Field2, ... FieldN : Integer;
end;
TMyList = List<PMyList>;
要订购具有条件的列表,请选择运行时(例如:field2然后field2,或者:field3然后field1然后field2等)有某种解决方案,或者我需要为我想要的订单的所有可能组合做一个比较构造?
For order the list with criteria choose to runtime (for example: field2 then field2, or: field3 then field1 then field2 etc) there is some solution or i need to do a compare construct for all combination possibile of order that i want?
我的想法是,如果记录为N字段,我认为是这样定义的数组:
Mine idea was, if record is N field, i have thinked to a array so defined:
MyArray = array [1..n] of Integer;
并将一个累进值分配给确定sord条件的数组元素,例如,如果MyArray如下:
and assign a progressive value to elements of array that determine criteria of sord for example if MyArray is as:
MyArray = (5, 1, 3, 4, 2)
表示我的列表需要首先对field5进行排序,然后对field1,然后对field3,再对于field4,再对field2进行排序。
我的问题是:我可以使用一个唯一的结构比较列表吗?
mean that my list need to be sort first for field5, then for field1, then for field3, then for field4, then for field2. Mine question then is: can i to do it using one only construct compare for my list?
非常感谢您的帮助。
推荐答案
我将基于您的上一个问题。我还要将 MyArray
重命名为 FieldPriority
。
I'm going to base the notation on your previous question. I'm also going to rename MyArray
as FieldPriority
.
因此, FieldPriority [1]
标识主要比较字段, FieldPriority [2]
标识辅助比较字段,
So, FieldPriority[1]
identifies the primary comparison field, FieldPriority[2]
identifies the secondary comparison field and so on.
在此位置,您的比较函数如下所示:
With this in place your compare function looks like this:
type
TMyRecord = record
Value: array [1..5] of Integer;
end;
function Compare(const Left, Right: TMyRecord): Integer;
var
i, Field: Integer;
begin
for i := 1 to 5 do
begin
Field := FieldPriority[i];
Result := CompareInt(Left.Value[Field], Right.Value[Field]);
if Result<>0 then
exit;
end;
end;
如果将记录中的整数声明为数组而不是单独声明,则效果会更好。
It all works much better if the integers in your record are declared as an array rather than individually. That allows you to index them as I do here.
自然地,所有这些都可以泛化为处理任意大小的数组。
Naturally this could all be generalised to handle arbitrary sized arrays.
这篇关于带条件的订单清单选择运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!