如何搜索通用 TList收藏?
我有一个 TActivityCategory 集合,
TList<TActivityCategory>
其中有一个字符串类型的 Name 属性,并且我想使用 Name 属性搜索 TList。
我在 TList<> 中看到 BinarySearch但这需要 TActivityCategory 的实例。我只想传递名称字符串。
我该怎么做呢?
Possible Duplicate:
How can I search a generic TList for a record with a certain field value?
I have a collection of
TList<TActivityCategory>
TActivityCategory has a Name property of type string and I want to search the TList using the Name property.
I see BinarySearch in the TList<> but that would require an instance of TActivityCategory. I just want to pass the string for a name.
How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
创建列表时,您可以传入比较器。 Generics.Defaults 单元中有一些比较器类,您可以在其中传递一些匿名方法来比较两个元素。它们用于多种方法,例如 IndexOf、Contains 或 Sort。
例子:
When you create the list you can pass in a comparer. There are some comparer classes in the Generics.Defaults unit where you can pass in some anonymous method to compare two elements. They are used for several methods like IndexOf, Contains or Sort.
Example:
如果您没有要搜索的实例,则必须自己进行搜索。可以通过三种基本方法来执行此操作:
TDictionary
。无需搜索,但您需要编写一些代码来保持两者同步。If you don't have an instance to search for, you have to do your own search. There are three basic ways to do this:
TDictionary<string, TActivityCategory>
alongside the list. No searching required, though you need to write some code to keep the two in sync.坦率地说,考虑到基于比较器的方法所需的所有样板,编写您自己的搜索例程可能是最简单的:
To be perfectly frank, and considering all the boiler plate required for a comparer based approach, it may just be simplest to write your own search routine: