Creating a new collection from an existing collection

  • Thread starter Thread starter marcus.wade
  • Start date Start date
M

marcus.wade

Hi,

I have a vb.net class collection which contains many instances of a
country class. Each country class has properties such as name, id,
currency etc.

The collection has been created without any problem. What I want to do
now is create a new subset of this collection (in a new collection)
that only contains countries that have a currency of Euro.

Anyone got any ideas how/if this can be achieved. I don't want to hit
the database again so need to create it from the existing collection
object.

Thanks,

Marcus.
 
So what is the problem?
dim new_collection as new collection
for each _item in old_collection
if _item.currecy=euro then new_collection
next
 
Hi Boni,

Thanks for that... This is how I've implemented it at the moment.
However, it seems a bit clunky to have to loop through the collection
each time and pick out the items I want. What I'm after is a way to
filter the items out of the collection in one go... much like a would
with a dataset filter, and create a new collection from that.

Any ideas?

Marcus
 
The OO way to do this:

1. Create your own Collection class, CountryCollection (you may have
already done this).

2. Create an Interface:

Public Interface ICountryFilter
Function MatchesCriteria(ByVal cntr As Country) As Boolean
End Interface

3. Add a method on your collection, say:

Public Function Collection Subset(ByVal filter As ICountryFilter) As
CountryCollection

Dim matchingSubset as New CountryCollection

For each cnt As Country
If filter.MatchesCriteria(cntr) Then
matchingSubset.Add(cntr)
End If
Next

Return matchingSubset

End Function

4. Define any needed filters:

Public Class FilterByCurrency
Implements ICountryFilter

Private mDesiredCurrency as CurrencyEnum

Sub New(ByVal desiredCurrency as CurrencyEnum)
mDesiredCurrency = desiredCurrency
End Sub

Public Function MatchesCriteria(ByVal cntr As Country) As Boolean
Implements ICountryFilter.MatchesCriteria
Return (cntr.Currency = mDesiredCurrency)
End Function

End Class

5. Use them in a single line:

Dim filteredColl as CountryCollection = origCollection.Subset(new
FilterByCurrency(EuroCurrency))

Hope that helps!
Tom

PS - The above was psudoe-code and may need tweaking. Additionally,
this is overkill unless you will be filtering on other criteria.
 
Hi, Thnaks for your post. I'm not that familiar with Implements and
Interfaces so haven't been able to convert the psuedo code into a
working example, do you have a real code snippet you could send me
please?

It looks like this mechanism still loops through each country and
compares the currencies before adding them to the new collection? Can
you confirm?

Thanks again for your help!

Marcus
 
Back
Top