我有一个System.Collections.Generic.List的本地副本,该副本由相同类型的服务器列表填充。当服务器列表被更改(添加到列表中的项或从列表中删除的项)时,我的应用程序将收到通知。
作为对该通知的回应,我希望更新列表的本地副本。我不想清除本地副本,并将其完全替换为服务器副本。我想找出不同之处,删除被删除的,并添加被添加的。
做这件事最好的方法是什么?
发布于 2014-03-20 11:17:27
如果通知包含整个远程列表,则可以使用Linq的Except
List<int> localList = new List<int>() {1, 2, 3};
List<int> remoteList = new List<int>() {1, 2, 4};
var addedItems = remoteList.Except(localList);
var removedItems = localList.Except(remoteList);发布于 2014-03-20 11:16:54
是否可以通过某些键来识别每一项?如果是这样,那么您可以从键到项保存一个字典,当从服务器获得更新的列表时,您可以查找字典中的每个键并删除/更新相应的项。
若要从列表中删除项,可以将整个服务器数据复制到另一个字典中,并查阅本地列表的每个项。
这个解决方案的复杂性是O(n),而不是在列表上使用Except,后者是O(n^2)。
发布于 2014-03-20 11:20:38
这可以用LINQ来完成
string[] names1 = System.IO.File.ReadAllLines(@"../../../names1.txt");
string[] names2 = System.IO.File.ReadAllLines(@"../../../names2.txt");
// Create the query. Note that method syntax must be used here.
IEnumerable<string> differenceQuery =
names1.Except(names2);
// Execute the query.
Console.WriteLine("The following lines are in names1.txt but not names2.txt");
foreach (string s in differenceQuery)
Console.WriteLine(s);https://stackoverflow.com/questions/22531142
复制相似问题