c# - 使用 linq 从 select new 返回多行

标签 c# .net linq linq-to-objects

我们需要将数据从表中的行转置到输出表,以便为输入表中的每一行返回多行。 在输出的每一行中提取数据的逻辑取决于输入行的给定列中是否存在值。

例如

输入表

A、B、C、D、E、F

输出表

A、B、C,[如果 D 中存在值,则对 D 中的值进行一些操作]

A、B、C,[如果 E 中存在值,则对 E 中的值进行一些操作]

A、B、C,[如果 F 中存在值,则对 F 中的值进行一些操作]

为此,我打算这样做:

private IEnumerable<OutputRow> BuildOutputTable(DataTable inputTable)
{
    var outputRows = from inputRow in inputTable.AsEnumerable()
                     select new outputRow(inputRow, *delegateToProcessor*);
    return gbbOutputRows;
}

但这需要我遍历每个附加值列。 我可以避免这种情况,只传递一个委托(delegate),以便“选择新输出行”返回多行吗?

最佳答案

创建一个像这样的函数:

public IEnumerable<OutputRow> GetOutputRows(InputRow input)
{
    if ( ** some condition on input.D ** )
        yield return new OutputRow(inputRow, *delegateToProcessor*);
    if ( ** some condition on input.E ** )
        yield return new OutputRow(inputRow, *delegateToProcessor*);
    if ( ** some condition on input.F ** )
        yield return new OutputRow(inputRow, *delegateToProcessor*);
}

您的查询如下所示:

var outputRows = from inputRow in inputTable.AsEnumerable()
                 from row2 in GetOutputRows(inputRow)
                 select row2;

关于c# - 使用 linq 从 select new 返回多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13289422/

相关文章:

c# - 服务器/客户端套接字连接

c# - 在运行时获取 C# 中属性的字符串表示形式

C#检测进程退出

c# - 使用 OledbConnection 的 Linq to XML 和 Excel 之间的速度差异?

c# - 使用成员访问 lambda 表达式参数化 LINQ to SQL 谓词

c# - 值在枚举列表中

c# - 如何使用 Html AGility Pack 在 Xpath 中放置 OR 条件

c# - 访问 `this` : invalid in C#, 的字段初始值设定项在 Java 中有效吗?

c# - 声明匿名类型的列表

.net - ClickOnce 部署 CheckForDetailedUpdate 抛出异常