检查项目是否在列表中并删除旧项目
问题描述:
我有一个列表。当这个列表填充,我有这样的事情:检查项目是否在列表中并删除旧项目
List<T> {Soc1, Soc2, Soc3}
与Soc复杂的对象。然后我修改列表:删除SOC2,加SOC4:现在
List<T> {Soc1, Soc3, Soc4}
,在DB,我已经得到了第一个列表(1,2,3),我必须用新的更新(1,3- ,4)。如何在c#中执行此检查?我尝试使用列表方法包含
foreach(T t in oldList){
if(t.Contains(oldList)){
...}
用于添加新的项目(S),但我停止元素的是(在这个例子中SOC 2)不存在了删除。怎么做?由于
答
你可以做两个回路,并使用LINQ:当你修改列表(删除项目)
// add the new ones...
foreach (var newItem in newList.Where(n => !oldList.Any(o => o.Id == n.Id))) {
oldList.Add(newItem);
}
// remove the redundant ones...
var oldIds = oldList.Select(i => i.Id);
foreach (var oldId in oldIds) {
if (!newList.Any(i => i.Id == oldId)) {
oldList.Remove(oldList.First(i => i.Id == oldId));
}
}
答
的foreach将打破。因此,最好使用while代替。 您使用一段时间的旧列表来删除不再存在的元素,然后通过新列表添加新项目。
List<T> oldList = new List<T> { Soc1, Soc2, Soc3 };
List<T> newList = new List<T> { Soc1, Soc3, Soc4 };
int i = 0;
// Go trough the old list to remove items which don't exist anymore
while(i < oldList.Count)
{
// If the new list doesn't contain the old element, remove it from the old list
if (!newList.Contains(oldList[i]))
{
oldList.RemoveAt(i);
}
// Otherwise move on
else
{
i++;
}
}
// Now go trough the new list and add all elements to the old list which are new
foreach(T k in newList)
{
if (!oldList.Contains(k))
{
oldList.Add(k);
}
}