Search code examples
c#ienumerableicollection

Having trouble with an ICollection/IEnumerable operation - won't remove an occurrence


I'm using a FastObjectListView to enter S/Ns of units to a Disposition (sold, RMA, etc) and I enter a constant for the first S/N - "(Enter Serial)"

I'm using this same model in another section of code (RMA) but I'm missing something when trying to do the same operation for Disposition.

    public UnitHistory RemoveUnit(Unit unit)
    {
        if (unit == null)
        {
            return null;
        }

        IEnumerable<UnitHistory> seq = AssociatedUnits.Where(p => p.Unit.Equals(unit));
        var unitHistories = seq.ToList();
        if (unitHistories.Any())
        {
            List<UnitHistory> collection = new List<UnitHistory>();
            collection.AddRange(AssociatedUnits);
            collection.Remove(unitHistories[0]);
            AssociatedUnits.Clear();
            foreach (UnitHistory history in collection)
            {
                AssociatedUnits.Add(history);
            }

            unitHistories[0].Disposition = null;
            DisassociatedUnits.Add(unitHistories[0]);
            unitHistories[0].Unit.UnitHistory.Remove(unitHistories[0]);

            return unitHistories[0];
        }

        return null;
    }

The code won't remove unitHistories[0] from collection. This model does work in the following code:

    public RmaRepairNotes RemoveUnit(Unit unit)
    {
        if (unit == null)
        {
            return null;
        }

        IEnumerable<RmaRepairNotes> seq = AssociatedUnits.Where(p => p.Unit.Equals(unit));
        var unitRmaHistories = seq.ToList();
        if (unitRmaHistories.Any())
        {
            List<RmaRepairNotes> collection = new List<RmaRepairNotes>();
            collection.AddRange(AssociatedUnits);
            collection.Remove(unitRmaHistories[0]);
            AssociatedUnits.Clear();
            foreach (RmaRepairNotes note in collection)
            {
                AssociatedUnits.Add(note);
            }

            unitRmaHistories[0].Rma = null;
            DisassociatedUnits.Add(unitRmaHistories[0]);
            unitRmaHistories[0].Unit.RmaRepairNotes.Remove(unitRmaHistories[0]);

            return unitRmaHistories[0];
        }

        return null;
    }

AssociatedUnits is an ICollection in both classes.

EDIT - SOLUTION: I found a logic error in the Equals code of the UnitHistory class. Now it functions perfectly.


Solution

  • The UnitHistory Class had a logic error in the Equals function. Now that objects could be identified as being equal, the code functions perfectly.