Home > Blockchain >  C# - LINQ First() and an implicit reference?
C# - LINQ First() and an implicit reference?

Time:02-26

I have some code that at first glance makes no sense to me.

Question: Is there some kind of implicit reference happening here? It seems like only non-matched items are added and the first section of the 'if' is doing nothing. Am I correct in that? (I've added my comments (///) to what I understand to flush out my question). (//) comments are original code comments

 public static List<BAPresModel> MergeBudgetApprovalByProgramPMLists(
    List<BAPresModel> sourceList, List<BAPresModel> destList)
{
    /// we create this and use it but it seems to never impact destList that I can tell
    BAPresModel dstBA = new BAPresModel();

    // Merge sourceList into destList.
    foreach (BAPresModel sl in sourceList)
    {
        var qryDestList = from dl in destList
                          where sl.FiscalYearID == dl.FiscalYearID
                          where sl.X == dl.X
                          where sl.Y == dl.Y
                          select dl;
        if (qryDestList.Count() > 0)  // we found a match in the destination list.
        {
            /// I researched -First()- but don't see anything clarifying my question
            /// Is this creating a reference back to destList from dstBA somehow?
            dstBA = qryDestList.First();
            /// this applies the math (adding sl.X to dstBA.X )
            dstBA.X = Maths.AddNullableDecimals(dstBA.X, sl.X);
            dstBA.Y = Maths.AddNullableDecimals(dstBA.Y, sl.Y);
        }
        else  // no match, so add the sourceList item to the destination list.
        {
            destList.Add(sl);
        }
    }

    /// as far as I can tell the only thing this method actually does is return the original
    /// destList with 'sl' matched items added to it
    /// all of the work on dstBA is useless??
    return destList;
}

Thank you for your time and assessment

CodePudding user response:

assuming BPAPresModel is a class

      dstBA = qryDestList.First();

effectively gets a pointer to the first matching entry returned by that query.

        /// this applies the math (adding sl.X to dstBA.X )
        dstBA.X = Maths.AddNullableDecimals(dstBA.X, sl.X);
        dstBA.Y = Maths.AddNullableDecimals(dstBA.Y, sl.Y);

so those 2 lines are changing it in the original destList

Class types in c# are called 'reference' types. Because in things like

   BAPresModel foo = SomeFunction();

foo is a reference to the actual object on the heap. If you are a c or c dev think

   BAPresModel *foo = SomeFunction();

so not an 'implicit' reference, an 'actual' reference

  • Related