views:

345

answers:

4

I have an array collection that I would like to limit to say 100 items. I tried setting up a filter function where the return was:

return (myAC.getItemIndex(item) > 100);

but the value was always -1. For whatever reason it couldn't find the item, even though the item is definitely there.

I'm able to do this with a while loop:

while(myAC.length > 100) myAC.removeItemAt(100);

Is there another way I can accomplish this? Thanks!

+3  A: 

Hmm, the best way I can think of is:

myAC = new ArrayCollection( myAC.toArray().slice(0,100) );

Of course, if you could control the size when the ArrayCollection is first constructed, that would be better.

Note that you cannot directly manipulate the source property of the object. From the docs of the source property of ArrayCollection:

The source of data in the ArrayCollection. The ArrayCollection object does not represent any changes that you make directly to the source array. Always use the ICollectionView or IList methods to modify the collection.

jason
+1  A: 

Try something like this:

myAc = new ArrayCollection(myAC.source.slice(0,100));

didn't test this so

Arno
A: 

First, your ">" should be "<" in your first line of code. You want to KEEP the first 100 items, not throw them out. I would bet the filtering is breaking because getItemIndex changes as you filter the array collection. Since you're always discarding the beginning part, nothing can ever be in it.

Not sure, but it's a start

Sean Clark Hess
A: 

I would wrap ArrayCollection in a class called LimitedArrayCollection that takes the limit as an optional compiler argument. Then override the appropriate public methods ( addItem, etc ) that would affect this sort of functionality. This is going to be much cleaner from a development and reuse standpoint. It will remove any ambiguity you are going to inevitably face when trying to use filters or other clever approaches.

Joel Hooks