c# - How to optimize code that changes a value deeply nested in an object graph -


below crude for-loop illustrate need do.

basically, if there 'variable' objects property 'name' containing text "tcc#", want change 'type' property (not .net type) 'variabletype.text'.

the code going run on 4800 parsedcard variables , takes stupid amount of time (about 10 minutes) iterate through list , write line debug console.

parsedcard has  ienumberable functions have  ienumberable groups have  parseresults have  ienumberable variables 

this such simple problem i've tried sorts of variations using linq can't find performs (less 10 seconds).

    private void adjusttccvariables(ilist<parsedcard> parsedcards)     {             (var = 0; < parsedcards.count; i++)         {             var parsedcard = parsedcards[i];             (var j = 0; j < parsedcard.functions.count(); j++)             {                 var function = parsedcard.functions.tolist()[j];                 (var k = 0; k < function.groups.count(); k++)                 {                     var group = function.groups.tolist()[k];                     (var l = 0; l < group.parseresult.variables.count(); l++)                     {                         var variable = group.parseresult.variables.tolist()[l];                         if (variable.name.contains("tcc#"))                         {                             //variable.type = variabletype.text;                             debug.writeline($"need change variable @ [{i}][{j}][{k}][{l}]");                         }                     }                 }             }         }     } 

i've tried linq doesn't change 'variable.type' of input list (i suspect because creates new copy of objects in memory , assignment isn't affected 'parsedcards' ienumerable @ all:

    private void adjusttccvariables(ienumerable<parsedcard> parsedcards)     {         var targetvariables =             parsedcards.selectmany(x => x.functions.selectmany(z => z.groups))                 .selectmany(x => x.parseresult.variables.where(v => v.name.contains("tcc#")));         ;         foreach (var variable in targetvariables)         {             variable.type = variabletype.text;         }     } 

as mentioned, bottleneck in iterations .tolist() calls.

since mention want edit variable.type property, solve this.

var variables = parsedcard in parsedcards                 function in parsedcard.functions                 group in function.groups                 variable in group.parseresult.variables                 variable.name.contains("tcc#")                 select variable;  foreach (var variable in variables) {     variable.type = variabletype.text; } 

you don't need know other variable objects need changing, don't need indexes , other variables. select need know, , change it.

this way not know indexes, debug.writeline(...); line won't work.


Comments