如何在LINQ C#中更改forach和foreach循环# [英] How can I change for and foreach loop in LINQ C#

查看:315
本文介绍了如何在LINQ C#中更改forach和foreach循环#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我不知道如何根据我的情况更改linq和foreach循环



Foreach



Hi All,

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

Foreach

//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





For Loop

//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(" ", "");
                }
            }





这一个,如何更改LINQ。是否有可能在LINQ如果有人知道那么请指导我。



谢谢



什么我试过了:



根据我的情况搜索google中的一些代码



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

推荐答案

以下是如何实现所需的LINQ转换:



转换为foreach构造的第一个代码片段 -



Here is how you can achieve the desired LINQ conversion:

Conversion for your first code snippet of foreach construct -

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

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

            });





在你的第二个代码片段中,有一个外部foreach循环和一个内部for循环。您已经要求将for循环转换为LINQ查询,这在技术上是不可能的。最多可以将外部foreach构造转换为LINQ查询。方法如下:





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:

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(" ", "");
                    }
                });


这篇关于如何在LINQ C#中更改forach和foreach循环#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆