-1

我想在 LINQ中使用带有 DefaultIfEmpty 子句的动态表达式和查询来获取两个集合中不匹配或不匹配的所有行。最终目标是获得两个表连接的增量。

在表 AI 中有:

Name | Description       | Type
A    | This is something | 1
B    | Something else    | 2
C    | Where have I gone | 1

在表 BI 中有:

Name | Description        | Type
A    | This is something  | 1
B    | Life is wonderful  | 2
D    | What happened to C | 2

我想得到如下结果:

Column      | Table A        | Table B
Name        | B              | B
Description | Something else | Life is wonderful
Type        | 2              | 2
---
Column      | Table A           | Table B
Name        | C                 | null
Description | Where have I gone | null
Type        | 2                 | null
---
Column      | Table A | Table B
Name        | null    | D
Description | null    | What happened to C
Type        | null    | 2
4

1 回答 1

0

这个答案不使用动态表达式。但是,正是我想出的解决方案给了我正在寻找的答案。

    var sql = table.SqlSelect;
    var dataLegacy = GetData(connections.Legacy, sql, table.TableName);
    var dataUpdate = GetData(connections.Update, sql, table.TableName);

    var compare = new List<CompareSet>();
    var jsonColumns = table.Json.ToList() ?? null;
    dataLegacy.AsEnumerable().ToList()
    .ForEach(legacyRow =>
    {
        DataRow updateRow = default(DataRow);
        if (table.KeyColumn.Any())
        {
            var keys = string.Join("|", table.KeyColumn.Select(kc => $"{legacyRow.Field<object>(kc)}"));
            updateRow = dataUpdate.AsEnumerable()
            .FirstOrDefault(y => keys == string.Join("|", table.KeyColumn.Select(kc => $"{y.Field<object>(kc)}")));
        }
        if (updateRow == null || JsonConvert.SerializeObject(legacyRow.ItemArray) != JsonConvert.SerializeObject(updateRow.ItemArray))
            compare.Add(new CompareSet(compare.Count, legacyRow, updateRow, jsonColumns));
    });
    dataUpdate.AsEnumerable().ToList()
    .ForEach(updateRow =>
    {
        DataRow legacyRow = default(DataRow);
        if (table.KeyColumn.Any())
        {
            var keys = string.Join("|", table.KeyColumn.Select(kc => $"{updateRow.Field<object>(kc)}"));
            legacyRow = dataLegacy.AsEnumerable()
            .FirstOrDefault(y => keys == string.Join("|", table.KeyColumn.Select(kc => $"{y.Field<object>(kc)}")));
        }
        if (legacyRow == null)
            compare.Add(new CompareSet(compare.Count, legacyRow, updateRow, jsonColumns));
    });
    if (compare.Any())
    {
        compare.OrderBy(c => c.OrderBy)
        .Dump($"{table.SchemaTable} ( {compare.Count()} / {dataLegacy.Rows.Count} / {dataUpdate.Rows.Count} rows )", TableDumpDepth);
    }
    else
    {
        "No differences found in data".Dump($"{table.SchemaTable} ( 0 / {dataLegacy.Rows.Count} / {dataUpdate.Rows.Count} rows )");
    }
于 2020-04-16T12:37:45.860 回答