There is no need to try to avoid For Each loops on large amounts of data

@postwick thanks for shifting this discussion topic to facts
@jeevith thanks for your involvment

I tried to avoid ongoing discussions from the past as the problem is not LINQ, For Each Defects or dramatic performance issues. It was more about misstaking Learning topics, mixing up LINQ benefits along with no present defects of other options. Also it was ignoring the nature and misuse of LINQ.

However as there are some topics added to the Blog/Tutorial pipeline, a preview already was released (LINQ vs Loops like for, for each and while - #2 by ppr), so its ok to step in within this discussion as an made exception.

First of all: Nothing is wrong, bad or else using For each … Activity

#Case 1
grafik

first of all it will not update every fith row:
grafik

it will update every record where current item last digit is a 5

Updating every five rows will be done with a mod check
grafik
grafik

Doing task 1 with a LINQcould look like below. Kindly note: LINQ Suggestion is one of many option

ra1 = {"Mary", 28, Dallas}
ra2 = {"Tom",27, Miami}

dtData =
(From x in Enumerable.Range(1,1000000)
let ra = If(x Mod 5 = 0, ra2, ra1)
Select r=dtData.Rows.Add(ra)).CopyToDataTable

Here we only use CopyToDataTable for psychological reasons and it is not needed

Case 2:
grafik

is similar to for each row, filter datatable activities (losing reference to original datatable etc)
approaches, but can be avoided by following:

  • feed with LINQ the already filtered rows into a for each (and do not use for each row)
  • update City
    grafik

And thats all, just move only the needed rows

Case 3:
is done with Case 2 and a split and merge datatable can be avoided

1 Like