vb.net - Find an item in an List(Of T) by values x, y, and z -
i have following setup:
class property x string property y int property z string end class class collofa inherits list(of a) end class
what item property in collection can say:
dim c new collofa c.item("this", 2, "that")
i have tried implementing following in collofa:
class collofa inherits list(of a) default public overridable shadows readonly property item(byval x string, byval y integer, byval z string) ' want like: ' foreach item in me see if matches these 3 things end end property end class
i know predicates, struggling how set criteria of predicate (i.e. passing x, y, , z).
has implemented similar?
here's 2 ways came accomplish question. 1 way uses linq query syntax filter; second uses custom object hold predicate parameters , uses object perform filter.
using linq syntax in item property:
default public overridable shadows readonly property item(byval x string, byval y integer, byval z string) ienumerable(of a) return (from thea in me (thea.x = x , thea.y = y , thea.z = z) select thea) end end property
the other way create predicateparameter class hold parameters , delegated method used execute filter. saw on msdn comment - here's link. here's class:
class predicateparams public sub new(byval thea a) criteria = thea end sub public property criteria public function ismatch(byval thea a) boolean return (thea.x = criteria.x , thea.y = criteria.y , thea.z = criteria.z) end function end class
and here's property in collofa class uses it:
public overridable shadows readonly property itempred(byval x string, byval y integer, byval z string) ienumerable(of a) dim preda new preda.x = x preda.y = y preda.z = z dim pred new predicateparams(preda) return me.findall(addressof pred.ismatch) end end property
lastly, here's console runner test this.
sub main() dim mycoll new collofa() index = 1 100 dim ana new a() ana.x = (index mod 2).tostring() ana.y = index mod 4 ana.z = (index mod 3).tostring() mycoll.add(ana) next dim matched ienumerable(of a) = mycoll.item("1", 3, "2") dim matched2 ienumerable(of a) = mycoll.itempred("1", 3, "2") console.writeline(matched.count.tostring()) 'output first search console.writeline(matched2.count.tostring()) 'output second search (s/b same) console.readline() end sub
hopefully helps. there may more elegant way this, didn't see one. (btw, work c#, vb.net little rusty.)
Comments
Post a Comment