好的,所以我需要获得两个数据行的键值配对差异。简而言之,我发送了一封电子邮件,让用户知道他们已对其个人资料进行了具体更改。 我已经知道行不同因为我正在使用SequenceEqual
来确定。
目前我已经编写并调试了以下代码:
if (currentRow.ItemArray.SequenceEqual(updatedRow)) { return; }
var updates = currentRow.ItemArray
.Where((o, i) =>
{
if (o == null && updatedRow[i] == null) { return false; }
else if (o == null && updatedRow[i] != null) { return true; }
else if (o.Equals(updatedRow[i])) { return false; }
return true;
})
.Select((o, i) =>
{
return new AppServices.NotificationData
{
Key = updatedRow.Table.Columns[i].ColumnName,
Value = Convert.ToString(updatedRow[i])
};
}).ToList();
但此代码存在两个问题:
ItemArray
中的每个值,然后在价值不同时构建一个键值对。 i
的{{1}}不正确(例如,如果第二列发生了更改Select
,发送到1
的索引实际上是Select
。老实说,这很有意义,但我不确定如何在这里得到我想要的内容。CONSTRAINT:我想在这里使用LINQ。
注意:我只是比较两行(即它不会通过行列表)。
我在这里尝试做什么的LINQ语句是什么?
更新:我觉得我只需要使用:
0
但问题是我不知道是什么字段,所以我无法建立一个键值对。换句话说,我只回到差异,但我不知道索引是什么,所以我不能根据这些值得到列名。
答案 0 :(得分:3)
老实说,使用for
循环不会损失太多代码清晰度。
public IEnumerable<AppServices.NotificationData> GetUpdates(DataRow currentRow, DataRow updatedRow)
{
if (currentRow.ItemArray.SequenceEqual(updatedRow)) yield break;
var length = currentRow.ItemArray.Length;
for(var i = 0; i < length; i++)
{
var currentCol = currentRow[i];
var updatedCol = updatedRow[i];
if (currentCol == null && updatedCol == null) continue;
else if (currentCol == null && updatedCol != null) continue;
else if (currentCol.Equals(updatedCol)) continue;
yield return new AppServices.NotificationData
{
Key = updatedRow.Table.Columns[i].ColumnName,
Value = Convert.ToString(updatedCol)
};
}
}
答案 1 :(得分:1)
var updates = currentRow.ItemArray
.Select((o, i) => new { Row = o, Index = i })
.Where(r => (r.Row == null && updatedRow[r.Index] != null)
|| (r.Row != null && updatedRow[r.Index] != null
&& !r.Row.Equals(updatedRow[r.Index])))
.Select(r => new
{
Key = updatedRow.Table.Columns[r.Index].ColumnName,
Value = Convert.ToString(updatedRow[r.Index])
}).ToList();
答案 2 :(得分:1)
一般来说,我认为在LINQ中使用数组索引值是一个“代码味道”,这是一个很好的例子:Where子句在生成一个新的值序列时,破坏了Select子句的错觉正在开发与以前相同的系列。
现在快速解决这个问题(尽管我认为这不是一个正确的解决方案),可能是交换你的Where和Select子句,基本上是:
if (currentRow.ItemArray.SequenceEqual(updatedRow)) { return; }
var updates = currentRow.ItemArray
.Select((o, i) =>
{
if (o == null && updatedRow[i] == null || o.Equals(updatedRow[i])) { return null; }
else return new AppServices.NotificationData
{
Key = updatedRow.Table.Columns[i].ColumnName,
Value = Convert.ToString(updatedRow[i])
};
}).Where(o => o != null).ToList();