[英]Use DefaultIfEmpty in Dynamic Expressions and Queries in LINQ
I want to use Dynamic Expressions and Queries in LINQ with a DefaultIfEmpty clause to get all of the rows from the two sets that don't match, or don't have a match.我想在 LINQ 中使用带有 DefaultIfEmpty 子句的动态表达式和查询来获取两组不匹配或不匹配的所有行。 The end goal is to get the delta of the join of the two tables.
最终目标是获得两个表连接的增量。
In table AI have:在表 AI 中有:
Name | Description | Type
A | This is something | 1
B | Something else | 2
C | Where have I gone | 1
In table BI have:在表 BI 中有:
Name | Description | Type
A | This is something | 1
B | Life is wonderful | 2
D | What happened to C | 2
I would like to get the results as:我想得到如下结果:
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
This answer doesn't use Dynamic Expressions.这个答案不使用动态表达式。 However, it is the solution that I came up with, that gives me the answer I'm looking for.
但是,正是我想出的解决方案给了我正在寻找的答案。
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 )");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.