Searching an ArrayCollection fast and easy – mx:ArrayCollection
Posted on February 13, 2010 | No Comments
Let’s say your Flex project needs to maintain a large amount of data, like all the userdata from you big ass site. You can use several datastructures in Flex to store complex userdata, from XML to linked lists. However, perhaps the most useful and easiest structure is the Flex native ArrayCollection. Cheap Amoxil This structure gives you a lot for free, for instance.. searching for stuff.
Let’s say you have all of your users in “usersCollection” which is an ArrayCollection. A user object may contain things like “firstNamename”,”lastName”, “email”, “address” and so on. Now, what if you need to find a specific user like “John Rambo”. Then you’ll need to search both the first and last name fields. You could of course traverse the entire collection using a loop, checking every iteration. Hang on, there is a faster way using a cursor (it’s kinda lika a struct pointer if you’re a C person).
First you need to sort the collection
var mySort:Sort = new Sort();
mySort.fields = [new SortField('lastname')];
usersCollection.sort = mySort;
usersCollection.refresh();
Then we create the cursor, pointing to the first item in the collection at init.
var cursor:iViewCursor = usersCollection.createCursor;
Now, we need to search both first and last name, so we create a searchobject.
var sObj:Object = {firstname:"John",lastname:"Rambo"};
We buy viagra online order are now ready to do the actual search by using the findAny method cheap levitra generic of the cursor.
if(cursor.findAny(sObj)){
//We found him
}else{
//John Rambo is lost again
}
In order to get to the user we found we utilize the current property of the cursor.
var foundUser:Object = cursor.current;
Do keep in mind that the cursor is now pointing to the user found, so if we want the next user in the list we can simply go
“cursor.moveNext()”
Why should you use this method? It’s more flexible, it’s faster and uses less resources than the traditional iterative loop approach.
Comments
Leave a Reply
You must be logged in to post a comment.
Sameera at LinkedIn
