tags:

views:

289

answers:

1

Hi! I'm struggeling 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 perform the same operation. Thanks for any help.

Larsi

+7  A: 

Well, LINQ is more about querying than updating, so I'll still separate it into a LINQ query and then a foreach loop to do the 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 efficient in terms of memory, in that it loads all the changed rows into a dictionary (internally) so that it can quickly look up the changed rows based on the row ID - but it means the looping complexity is a lot smaller (O(n) + O(m) instead of O(n * m) if each row only matches a single changed row and vice versa).

Jon Skeet
+1 for separating tasks logically instead of cramming it all into a single linq-query. As someone answered to a question about the misconceptions about linq: It should be used for everything. =)
J. Steen