所以,我有一个树视图,其中一些行来自DataTable。当我获取数据表时,我想用以下基本规则更新树:
为此,我有一个字典,将Guid(DataTable中的主键)散列到树节点:
Dictionary<Guid, NoteNode> MyHashNoteToNode;
,其中NoteNode派生自TreeNode,并添加了LastEdit DateTime字段。到目前为止,如此平庸。
为了找到代表树和DataTable之间差异的3组,我编写了下面的代码。我很想听到有一个非常简单的Linq查询将返回3组(插入,编辑,删除),或者为我做一些简洁的事情,也许是我在某处遗漏的方法。或者这是非常优化的?
// Find all items that need inserting.
List<DataRow> toInsert = new List<DataRow>();
foreach (DataRow row in MyNotes.Rows)
{
NoteNode node = null;
MyHashNoteToNode.TryGetValue((Guid)row["ID"], out node);
if(node == null)
{
toInsert.Add(row);
}
}
// Find all items that need editing/changing.
List<DataRow> toEdit = new List<DataRow>();
foreach (DataRow row in MyNotes.Rows)
{
NoteNode node = null;
MyHashNoteToNode.TryGetValue((Guid)row["ID"], out node);
if(node != null)
{
if((DateTime)row["Edited"] != node.LastEdit)
{
toEdit.Add(row);
}
}
}
// Find all items that need deleting.
List<NoteNode> toDelete = new List<NoteNode>();
foreach (NoteNode node in MyHashNoteToNode.Values)
{
if (!MyNotes.Rows.Contains(node.Key))
{
toDelete.Add(node);
}
}
}
答案 0 :(得分:1)
从DataTable
制作词典的简单方法是
DataSet newData;
DataSet existingData;
var before = existingData.AsEnumerable().ToDictionary(
n => Guid.Parse(n.Field<string>("ID")),
n => n);
var after = newData.AsEnumerable().ToDictionary(
n => Guid.Parse(n.Field<string>("ID")),
n => n);
要找到需要工作的密钥,
var keysToInsert = after.Select(p => p.Key).Except(before.Select(p => p.Key));
var keysToDelete = before.Select(p => p.Key).Except(after.Select(p => p.Key));
var keysTheSame = before.Select(p => p.Key).Intersect(after.Select(p => p.Key));
要查找需要工作的行,
var nodesToInsert = keysToInsert.Select(k => after[k]);
var nodesToDelete = keysToDelete.Select(k => before[k]);
var nodesThatNeedUpdates = keysTheSame
.Where(k =>
before[k].Field<DateTime>("Edited") !=
after[k].Field<DateTime>("Edited"))
.Select(k => after[k]);