Andrew Truckle
Andrew Truckle

Reputation: 19197

Simplify a method with LINQ to update a series of nested property values

Can this be simplified?

public int ReplaceNameInHistoryForPublisher(string OldName, string NewName)
{
    int iSize = _DutyAssignments.Count;
    int iTotalReplaced = 0, iTotal = 0;

    try
    {
        for (int i = 0; i < iSize; i++)
        {
            DutyAssignmentEntry oEntry = _DutyAssignments[i];

            int iSizeAssign = oEntry.Assignments.Count;
            for(int iAssign = 0; iAssign < iSizeAssign; iAssign++)
            {
                if(oEntry.Assignments[iAssign].Name == OldName)
                {
                    oEntry.Assignments[iAssign].Name = NewName;
                    iTotal++;
                }
            }

            if(iTotal > 0)
            {
                _DutyAssignments[i] = oEntry;
                iTotalReplaced += iTotal;
            }
        }

        return iTotalReplaced;
    }
    catch (Exception ex)
    {
        SimpleLog.Log(ex);
        return 0;
    }
}

I have a List of DutyAssignmentEntry objects. Each of these objects has an Assignments property. As expected, that variable is a List of Assignment objects.

The Assignment object has a Name property which is what i am looking at to update.

My code works but I wondering if it can be improved with LINQ?

Upvotes: 0

Views: 705

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460268

Yes, you can simplify it:

public int ReplaceNameInHistoryForPublisher(string OldName, string NewName)
{
    var assignmentsToUpdate = _DutyAssignments
        .SelectMany(da => da.Assignments.Where(a => a.Name == OldName))
        .ToList();

    assignmentsToUpdate.ForEach(x => x.Name = NewName);

    return assignmentsToUpdate.Count;
}

But note that LINQ is not the right tool to update a collection but to query it. You can use it to find out what you have to update. I hide the loops in the LINQ query and in List<T>.ForEach.

Btw, Assignment is a reference type, so you can simply change the Name property, you don't need to overwrite this reference in the list with itself(_DutyAssignments[i] = oEntry).

Upvotes: 2

Related Questions