1

我需要通过添加与通用列表中的对象对应的行来创建一个表(LINQ 以替换 TableRow 创建中的 foreach)。我们可以使用 foreach 循环按照下面列出的方式进行操作。我们如何在没有 foreach的情况下使用LINQ实现此功能?

注意:对象中的每个属性都需要添加一个表格单元格。

 System.Web.UI.WebControls.Table tableControl = new Table();

 foreach (FinancialTransaction transaction in transactionsList)
        {
            TableRow row = new TableRow();

            TableCell cellLineNumber = new TableCell();
            cellLineNumber.Text = Convert.ToString(transaction.Line);
            row.Cells.Add(cellLineNumber);

            TableCell cellEmpID = new TableCell();
            cellEmpID.Text = Convert.ToString(transaction.EmpID);
            row.Cells.Add(cellEmpID);

            TableCell cellSSN = new TableCell();
            cellSSN.Text = transaction.SSN;
            row.Cells.Add(cellSSN);

            tableControl.Rows.Add(row);
        }
4

3 回答 3

3

您可以使用ForEachLINQ if transactionsListis List,但可以稍微提高可读性:

transactionsList.ForEach(transaction => {
     TableRow row = new TableRow();

     valueList = new object[] { 
                                  transaction.Line, 
                                  transaction.EmpID, 
                                  transaction.SSN 
                              };

     row.Cells.AddRange(valueList.Select(value => CreateCell(value))
                            .ToArray());

});

private TableCell CreateCell(object cellText)
{
    TableCell cell = new TableCell();
    cell.Text = Convert.ToString(cellText);

    return cell;
}
于 2012-09-25T06:43:02.013 回答
1

您还可以使用Aggregate

var tableControl = transactionsList.Aggregate(new Table(), (acc, transaction) => 
{  
    TableRow row = new TableRow();

    TableCell cellLineNumber = new TableCell();
    cellLineNumber.Text = Convert.ToString(transaction.Line);
    row.Cells.Add(cellLineNumber);

    TableCell cellEmpID = new TableCell();
    cellEmpID.Text = Convert.ToString(transaction.EmpID);
    row.Cells.Add(cellEmpID);

    TableCell cellSSN = new TableCell();
    cellSSN.Text = transaction.SSN;
    row.Cells.Add(cellSSN);

    acc.Rows.Add(row);

    return acc;
});
于 2012-09-25T07:11:46.687 回答
0

Linq 本身的 foreach 怎么样?或检查链接

也可以创建自己的扩展方法

于 2012-09-25T06:31:16.317 回答