6.2.2.3 搜索和过滤 - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
6.2.2.3 搜索和过滤
If you have collections of objects you often need to sort and filter them. Use the findAll and grep tags for these tasks:The Or using a regular expression:The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The
如果你的对象是集合,那么你经常需要排序和过滤。使用findAll和grep标签可以完成这些任务:Stephen King's Books: <g:findAll in="${books}" expr="it.author == 'Stephen King'"> <p>Title: ${it.title}</p> </g:findAll>
expr attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for example filtering by class:<g:grep in="${books}" filter="NonFictionBooks.class"> <p>Title: ${it.title}</p> </g:grep>
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/"> <p>Title: ${it}</p> </g:grep>
books variable is a collection of Book instances. Since each Book has a title, you can obtain a list of Book titles using the expression books.title. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!
Stephen King's Books: <g:findAll in="${books}" expr="it.author == 'Stephen King'"> <p>Title: ${it.title}</p> </g:findAll>
expr属性使用一个Groovy表达式来作为过滤器。grep标签完成类似的任务,比如要过滤对象类:<g:grep in="${books}" filter="NonFictionBooks.class"> <p>Title: ${it.title}</p> </g:grep>
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/"> <p>Title: ${it}</p> </g:grep>
books变量是一个Book实例的集合。因为每一个Book都有title,你可以使用表达式books.title来获取Book标题的列表。Groovy将会自动地对集合迭代,获取每一个标题,最终返回一个新的列表。

