0

我有一个带有子集合的实体

给定一个 ids => NewIdList 的列表,我想要来自不在 NewIdList 中的 Children 的项目,并为那些在 NewIdList 但不在 Children 中的 id 创建新项目。

原谅伪代码:)

myEntity.Children = new [] {2, 3}

var newIdList = new [] {1, 2, 4, 5}

// Do Magic

myEntity.Children = new [] {1, 2, 4, 5}

// Note that '2' would not have a created date 
// or audit record as it was in the list before Do Magic occured

我打算做这样的事情

var newIdList = new [] {1, 2, 4, 5};
var childrenToRemove = myEntity.Children.Where(c=> !newIdList.Contains(c));
var childrenToAdd = newIdList.Where(c => myEntity.Children.Contains(c));

foreach(var cr in childrenToRemove){
    myEntity.Children.Remove(cr);
}

foreach(var ca in childrenToAdd ){
    myEntity.Children.Add(cr);
}

这是实现这一目标的最佳方法吗……感觉有点笨拙

4

1 回答 1

1
var list1 = new[] { 2, 3 };
var list2 = new[] { 1, 2, 4, 5 };

var excepts = list1.Except(list2);
var union = list1.Union(list2);
var newlist = union.Except(excepts);

Console.WriteLine(string.Join(",", newlist));
于 2013-11-14T06:18:37.140 回答