search a Generic list

后端 未结 2 1537
孤街浪徒
孤街浪徒 2021-01-22 21:02

I \'m trouble understanding in modifying the solution from GENERIC SEARCH as my class is more complex and I need to create several different search functions

pro         


        
2条回答
  •  情书的邮戳
    2021-01-22 21:37

    TList supports searching for items using either linear or binary search. With binary search, the algorithm assumes an ordering. That's not appropriate for your needs. Linear search seems to me to be what you need, and it's available through the Contains method.

    The problem is that Contains assumes that you are searching for an entire instance of T. You want to pass a single string to Contains but it won't accept that. It wants a complete record, in your case.

    You could provide a Comparer that only compares a single field. And then pass Contains a record with just that one field specified. But that's pretty ugly. Frankly the design of this class is very weak when it comes to searching and sorting. The fact that the comparer is a state variable rather than a parameter is a shocking lapse in my view.

    The bottom line is that TList does not readily offer what you are looking for without resorting to ugliness. You should probably implement an old-fashion loop across the list to look for your match.

    Note that I'm assuming you want to provide a single string and search for an entry that has a field matching the string. If in fact you do want to provide a complete record and match every field, then Contains does what you need, with suitable Comparer using a lexicographic ordering.

提交回复
热议问题