list中抽出某一个字段的值_如何在一个通用的TList中搜索具有某个字段值的记录?...

bd96500e110b49cbb3cd949968f18be7.png

Everything about generic TList. I have this structure:

Type

TExtract = record

Wheel: string;

Extract: array [1..5] of Byte;

end;

TExtractList = TList

TEstr = record

Date: TDate;

Extract: TExtractList;

end;

TEstrList = TList;

The main list is TExtrList and in this list I have all dates and for date all wheel with that date. I want to search if a date exists or not. If not exist I add in sublist TExtractList of Extract from TEstr the info. When I search from TExtrList Delphi asks me about TEstr type. I need to search for Date only. So how can I search for single field in a generic TList?

PS: I have deleted last post because here I have tried to explain better.

解决方案

Here we go again.

You should use the built-in TList.BinarySearch() function, even if it rightfully asks for a TEstr record as a parameter. You'll first need to use TList.Sort() to sort the list using the same criteria as for the search, then call BinarySearch() to find your record.

Here's a function that does both (sort and search):

uses Generics.Defaults; // this provides TDelegatedComparer

uses Math; // this provides Sign()

function SearchList(Date:TDate; Sort:Boolean; List:TList): Integer;

var Comparer: IComparer;

Dummy: TEstr;

begin

// Prepare a custom comparer that'll be used to sort the list

// based on Date alone, and later to BinarySearch the list using

// date alone.

Comparer := TDelegatedComparer.Construct(

function (const L, R: TEstr): Integer

begin

Result := Sign(L.Date - R.Date);

end

);

// If the list is not sorted, sort it. We don't know if it's sorted or not,

// so we rely on the "Sort" parameter

if Sort then List.Sort(Comparer);

// Prepare a Dummy TEstr record we'll use for searching

Dummy.Date := Date;

// Call BinarySearch() to look up the record based on Date alone

if not List.BinarySearch(Dummy, Result, Comparer) then

Result := -1;

end;

BinarySearch assumes the list is sorted (that's the essence of binary searching!). On your first call you need to set Sort=True so the list is properly sorted. On subsequent calls Sort should be False. Of course, in actual use you'd probably have separate routines for searching and sorting, and you'd probably have them as methods of a class descending from TList (to make things easyer). I places both in the same routine for dempnstration purposes.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值