Click here to Skip to main content
15,881,589 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This is my C# for loop code..

Program:

C#
string[] Array1=some row values;
for(int i=0; i < Array1.row.count; i++)
{
    for(int j=0; j < Array1.row.count; j++)
    {
        //Some code
    }
}


But I have 50,000 records in database. For loop is slowly get the data, so I need Linq.. Please tell the answer how to use the Linq in C#...
Posted
Updated 19-Mar-15 0:32am
v2
Comments
BillWoodruff 19-Mar-15 7:10am    
Your loop code AS SHOWN will iterate the square of the number of rows; I am sure you do not really want the inner-loop to iterate over the entire array again.

Why do you think using Linq would be faster ?
Cherma sundar A 19-Mar-15 7:30am    
I don't know my friend suggest me..... The inner loop also needed for my functionality. I need any other way for that problem..
Dave Kreskowiak 19-Mar-15 8:20am    
Linq is not going to make this "faster". There also is no way to suggest anything in Linq because it deals with the code that you left out of your loop code snippet.

The only way to make this code faster is to figure out a way to avoid the inner loop entirely.
BillWoodruff 19-Mar-15 10:48am    
If you really need to operate on each row in your database, then you should use nested for-loops.

Linq becomes useful when you need to filter the results of a database query to operate on only a limited range of the Rows in your database; however, the "big win" is when you create a stored procedure (in some query language, that hopefully can be compiled) that has the "filtering logic" that the database executes, so you get back only the Rows you need to work-on.

The less the size of the data that the database sends back to you "over the wire," the greater the benefit in terms of speed.
Andy Lanng 19-Mar-15 13:13pm    
Perhaps there is a way to avoid the nested loop using linq, but you need to tell us the scenario: Why do you need to loop through each row for each row in the data? Is there a comparative operation between the records you are trying to achieve? If so then please explain it. Then maybe we can help.
If there is no way to avoid comparing every row with every other then I doubt linq can help you much.
If you only need to compare x with y and not also y with x then you could have an (n^2)/2 (half the work) by removing the first item from the second list before the loop, and then remove the first item again each loop. This assumes that you don't need to compare x with x

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900