jeudi 21 décembre 2017

Increment property name, when adding to ObservableCollection

I have a collection of components, where the component name is unique for each one of them. When the user adds a new component to this collection, the component name should increment by 1, depending on the number of already existing components. When the user removes a component, the component name given to a newly added component should still be unique.

Right now I am looping through the components in the collection, to get the total amount of each, and increment the counter for every one that is equal to the component to be added.

private void OnComponentAdded()
        {
            if (SelectedComponent != null)
            {
                var numberOfDuplicates = 0;
                foreach (var item in ComponentsForEquipment)
                {
                    if (item.ComponentId == SelectedComponent.ComponentId)
                    {
                        numberOfDuplicates++;
                    }
                }
                numberOfDuplicates++;
                SelectedComponent.ComponentName = SelectedComponent.ComponentType + numberOfDuplicates.ToString();

                var match = ComponentsForEquipment.Where(c => c.ComponentName == SelectedComponent.ComponentName).SingleOrDefault(); //componentname already exists
                if (match == null)
                {
                    ComponentsForEquipment.Add(SelectedComponent);
                }
            }
            else
            {
                MessageBox.Show("Please select a component before adding.", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
            }

        }

But if the user removes a component and then adds it again, the component name will not be unique. Therefore I added the if statement to check for a match by component name. The problem is if the user removes a previously added component, the new name generated will not be unique.

Here is an example of duplicate components in the collection: enter image description here

Aucun commentaire:

Enregistrer un commentaire