We help IT Professionals succeed at work.

Strongly Typed Object in Array Collection

I have an ArrayCollection containing a list of strongly typed objects. If the object is already in the ArrayCollection, I need to prevent the user from adding it again. Any advice on how to accomplish? Thanks for your help. Sorry for the newb question.
Comment
Watch Question

Would the object being added be the actual object or a different object but just with the same properties?

If it is the actual object just use: getItemIndex() if it returns -1 then its not in the list.

http://livedocs.adobe.com/flex/3/langref/mx/collections/ListCollectionView.html#getItemIndex()



Author

Commented:
Fuzzy,
I'll be adding the actual object. So it looks like I pass in the property and if it is -1 then it is not in the AC. For example Employee object with empID = 1 if it returns a -1 then it is not in the AC? Thanks.

Author

Commented:
Sorry for the hasty response. As you mention, it's looking for the object itself. So I'll pass in Employee. If it does not find it it will return -1, rather than a property.

Author

Commented:
I've given this a go but I seem to keep getting a -1.
For one reason or another it probably isn't the same object. However as you have a unique property in each object, you could do a simple loop through the collection and test each employee id.

I think I've attatched code snippet but doing it from phone, so not sure?
private function isEmployeeInList(EmployeeList:ArrayCollection, empId:int):void
{
var:emp as EmployeeObject; 
for each emp in EmployeeList // start loop
{
if (emp.empId == empId) // test for match
{
return true; // is in list
} // end if
} // end loop
return false; // not in list

Open in new window

Or you can use an object to hold your objects and use strings to key each instance of your strongly typed object.  So instead of using Array.push(object), you would do something like Object[stObject.id] = stObject.  Where stObject is your strongly typed object.  Then you can loop through your "Collection" object with a for each.  Hope that helps.  Does it make sense?

~Ryan
And let me elaborate, because my wording was not the best.  So lets say you have these strongly typed objects of type Employee.  Each employee has a first name, last name, address, and some unique ID (like a database index or GUID).

You would then create a holder object (instead of an Array) to hold your employees:

var Employees:Object = new Object();

Then, you would populate that object with your Employees like so:

var emp:Employee = new Employee(fname, lname, soc);  // Load employee from DB
Employees[emp.ID] = emp;

Hope that helps.

~Ryan