将带有聚合子句的 VB 代码转换为 C#

本文关键字:代码 VB 转换 子句 | 更新日期: 2023-09-27 18:30:58

我一直在尝试将以下代码从 VB 转换为 C#:

Dim rowsnotfound As DataRow() = (From rowstb2 As DataRow In dsNew.Tables("parts").Rows.OfType(Of DataRow)() Where (Aggregate rowstb1 As DataRow In dsOld.Tables("parts").Rows.OfType(Of DataRow)() Where ((rowstb1.Item("TRANSACTION")) = (rowstb2.Item("TRANSACTION")) And (rowstb1.Item("DESCRIPTION")) = (rowstb2.Item("DESCRIPTION")) And (rowstb1.Item("QTY")) = (rowstb2.Item("QTY")) And (rowstb1.Item("PART_NUM")) = (rowstb2.Item("PART_NUM"))) Into Count()) = 0).ToArray

我知道这将在计算机上显示为一长串代码,所以这里是代码聚合部分的片段,以便您可以更轻松地阅读它:

(Aggregate rowstb1 As DataRow In dsOld.Tables("parts").Rows.OfType(Of DataRow)() Where ((rowstb1.Item("TRANSACTION")) = (rowstb2.Item("TRANSACTION")) And (rowstb1.Item("DESCRIPTION")) = (rowstb2.Item("DESCRIPTION")) And (rowstb1.Item("QTY")) = (rowstb2.Item("QTY")) And (rowstb1.Item("PART_NUM")) = (rowstb2.Item("PART_NUM"))) Into Count())

我研究了聚合子句,并了解了它如何运作的基本知识。但是,我在将其转换为 C# 时遇到了很大的麻烦。任何帮助将不胜感激。

将带有聚合子句的 VB 代码转换为 C#

您正在执行的操作似乎等效于 SQL LEFT JOIN 操作,在该操作中,您希望在第一个集合中查找不在第二个集合中的元素。 您可以使用以下内容来执行此操作,而不必使用聚合:

IEnumerable<DataRow> newRows = dsNew.Tables["parts"].Rows.OfType<DataRow>();
IEnumerable<DataRow> oldRows = dsOld.Tables["parts"].Rows.OfType<DataRow>();
DataRow[] rowsNotFound = newRows
.GroupJoin(oldRows, 
    o => new 
        { 
            Transaction = o.Field<int>("TRANSACTION"), 
            Description = o.Field<string>("DESCRIPTION"), 
            Quantity = o.Field<int>("QTY"), 
            PartNumber = o.Field<string>("PART_NUM") 
        },
    i => new 
        { 
            Transaction = i.Field<int>("TRANSACTION"), 
            Description = i.Field<string>("DESCRIPTION"), 
            Quantity = i.Field<int>("QTY"), 
            PartNumber = i.Field<string>("PART_NUM") 
        },
    (o, i) => new {NewRow = o, OldRows = i})
.SelectMany(g => g.OldRows.DefaultIfEmpty(), (g, oldRow) => oldRow == null ? g.NewRow : null)
.Where(r => r != null)
.ToArray();

我不知道数据类型,所以我根据字段名称进行猜测。

我认为它会是这样的:

DataRow[] rowsnotfound = (
    from DataRow rowstb2 in dsNew.Tables("parts").Rows.OfType<DataRow>()
    where ((
            from DataRow rowstb1 in dsOld.Tables("parts").Rows.OfType<DataRow>()
            where (rowstb1["TRANSACTION"] == rowstb2["TRANSACTION"]
                && rowstb1["DESCRIPTION"] == rowstb2["DESCRIPTION"]
                && rowstb1["QTY"] == rowstb2["QTY"]
                && rowstb1["PART_NUM"] == rowstb2["PART_NUM"])
            select rowstb1).Count()) == 0).ToArray();