我有2个列表,当第一个列表中的项目不在第二个列表中时,我想删除这些项目。
public class ResolutionsRow
{
public String Name { get; set; }
public int ID { get; set; }
}
public List<ResolutionsRow> Categories { get; set; }
在以下Category.LoadForProject(project.ID)中返回IList
DeleteItems(Category.LoadForProject(project.ID), Categories);
private void DeleteItems(dynamic currentItems, dynamic items)
{
if (currentItems != null)
{
foreach (var existingItem in currentItems)
{
if (items.Contains(existingItem.Name))
items.Remove(existingItem.Name);
}
}
}
我收到错误消息
'System.Collections.Generic.List.Contains(MvcUI.Models.ResolutionsRow)'的最佳重载方法匹配有一些无效的参数。我的代码有什么问题,我该如何纠正?请帮助。
我已尝试将代码更改为,但我收到错误消息
错误6参数1:无法从'int'转换为API.Category'MvcUI \ Models \ ProjectModel.cs 255 44 MvcUI 错误5'System.Collections.Generic.ICollection.Contains(API.Category)'的最佳重载方法匹配具有一些无效参数MvcUI \ Models \ ProjectModel.cs 255 24 MvcUI
var categories = Category.LoadForProject(project.ID);
foreach (var item in Categories)
{
if(categories.Contains(item.ID))
{
}
}
答案 0 :(得分:2)
什么是items
?我猜这是ResolutionsRow
的列表 - 因此您需要搜索 项名称/ ID,而不是名称/ ID本身。
如果它们是相同的对象实例,那么只有Remove(existingItem)
才能工作,否则(如果它们是碰巧具有相同.Name
的不同对象实例):
items.RemoveAll(item => item.Name == existingItem.Name);
顺便说一下;你真的需要dynamic
吗?没有它,编译器会告诉你问题。它没有帮助你,并且很可能会导致很多问题(显式接口实现,lambdas等等 - 有些构造不是dynamic
的粉丝)
答案 1 :(得分:2)
这是简单的LINQ答案:
var currentItems = new int[] { 1, 2, 5, 6 };
var items = new int[] { 2, 3, 4, 5 };
var resultItems = items.Except(currentItems); // resultItems == new int[] { 3, 4 }
答案 2 :(得分:1)
更改
items.Contains(existingItem.Name);
和
items.Remove(existingItem.Name);
到
items.Contains(existingItem);
items.Remove(existingItem);
答案 3 :(得分:1)
您想使用items1.Except(items2)
答案 4 :(得分:0)
您的items.Contains
方法签名期望的类型与您提供的类型不同。看起来你提供的是字符串而不是ResolutionsRow。
答案 5 :(得分:0)