What is a linq query that will replace my two foreach

I am trying to figure out how to replace the two foreach below.

        public void UpdateChangedRows(List<Row> changedRows)
    {
        // How to write linq to update the rows (example code using foreach)
        foreach (Row row in table.Rows)
        {
            foreach (Row changedRow in changedRows)
            {
                if (row.RowId==changedRow.RowId)
                {
                    row.Values = changedRow.Values;
                }
            }
        }
    }

      

I think there would be a linq way to accomplish the same operation. Thanks for any help.

Larsi

0


a source to share


1 answer


Well, LINQ is more about queries than updating, so I'll still split it into a LINQ query and then a loop foreach

to update:

var query = from row in table.Rows
            join changedRow in changedRows on row.RowId = changeRow.RowId
            select { row, changedRow };

foreach (var entry in query)
{
    entry.row.Values = entry.changedRow.Values;
}

      



Note that this is less memory efficient as it loads all changed lines into a dictionary (internally) so that it can quickly search for changed lines based on the line id, but that means the looping complexity is much less ( O(n) + O(m)

instead of O(n * m)

if each line matches only one changed line and vice versa).

+7


a source







All Articles