Click here to Skip to main content
15,886,069 members
Please Sign up or sign in to vote.
1.89/5 (3 votes)
See more:
Hi All,

I don't know how to change for and foreach loops in linq as my situation

Foreach

C#
//GrdJobno is of type System.Web.UI.WebControls.GridView
foreach (TableCell cell in GrdJobno.HeaderRow.Cells)
            {
                if (cell.Text != " ") // AUTOMATICALLY GENRATION SPACE " "
                    dtCustomers.Columns.Add(cell.Text);
            }


For Loop

C#
//dtCustomers is of type System.Data.DataTable
foreach (GridViewRow row in GrdJobno.Rows)
            {
                dtCustomers.Rows.Add();
                for (int i = 1; i < row.Cells.Count; i++)
                {
                    dtCustomers.Rows[row.RowIndex][i - 1] = row.Cells[i].Text.Replace(" ", "");
                }
            }


This one, How can I change in LINQ. Is it possible in LINQ if anyone know then please guide me.

Thanks

What I have tried:

Searched some code in google based on my situation
Posted
Updated 4-Jan-17 16:15pm
v2
Comments
Thomas Daniels 24-Dec-16 2:46am    
To be honest, I don't see a reason why you would have to change this code into LINQ.
OriginalGriff 24-Dec-16 4:58am    
What have you tried?
Not "what have you googled?" - what you you actually done to try and generate the Linq code?
F-ES Sitecore 24-Dec-16 8:02am    
Using linq will make your code slower, there's no point in doing it.
Maciej Los 3-Jan-17 2:04am    
Sorry, but your question is not clear. Can you provide more details? Why do you want to replace for/foreach into Linq expression?
Rasik Bihari Tiwari 4-Jan-17 19:44pm    
What is the data type of GrdJobno and dtCustomers variable? I request you to please post complete code.

1 solution

Here is how you can achieve the desired LINQ conversion:

Conversion for your first code snippet of foreach construct -

C#
GrdJobno.HeaderRow.Cells.OfType<TableCell>().ToList<TableCell>().ForEach(cell => {

                if (cell.Text != " ")
                    dtCustomers.Columns.Add(cell.Text);

            });


In your second code snippet there is an outer foreach loop and an inner for loop. You have asked for conversion of for loop into a LINQ query which is technically not possible. At best you can convert the outer foreach construct into a LINQ query. Here is how:

C#
GrdJobno.Rows.OfType<GridViewRow>().ToList<GridViewRow>().ForEach(
                row =>
                {
                    dtCustomers.Rows.Add();
                    for (int i = 1; i < row.Cells.Count; i++)
                    {
                        dtCustomers.Rows[row.RowIndex][i - 1] = row.Cells[i].Text.Replace(" ", "");
                    }
                });
 
Share this answer
 
v3

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