2010-07-13 132 views
0

我有2个列表,我想删除第一个列表中的项目不存在于第二个列表中的项目。如何比较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); 
        } 
       } 
      } 

我有错误消息

的最好的overlo 'System.Collections.Generic.List.Contains(MvcUI.Models.ResolutionsRow)'的匹配方法有一些无效的参数。我的代码出了什么问题,我该如何纠正它?请帮助。

我试图改变代码,但是我有错误消息

错误6参数1:不能从“INT”转换为API.Category” MvcUI \模型\ ProjectModel。 CS 255 44 MvcUI 错误5的最好重载方法匹配 'System.Collections.Generic.ICollection.Contains(API.Category)' 具有一些无效参数MvcUI \模型\ ProjectModel.cs 255 24 MvcUI


var categories = Category.LoadForProject(project.ID); 
       foreach (var item in Categories) 
       { 
        if(categories.Contains(item.ID)) 
        { 

        } 
       } 

回答

1

变化

items.Contains(existingItem.Name); 

items.Remove(existingItem.Name); 

items.Contains(existingItem); 

items.Remove(existingItem); 
+0

它在达到这部分代码之前失败。 – learning 2010-07-13 11:54:18

+0

我仍然有错误消息 'System.Collections.Generic.List .Contains(MvcUI.Models.ResolutionsRow)'的最佳重载方法匹配有一些无效参数 – learning 2010-07-13 11:59:08

+0

在最后代码示例在你编辑的答案中,将if(categories.Contains(item.ID))'改为'if(categories.Contains(item))'。其他人发布的基于LINQ的选项可能是更好的选择,顺便说一句。你有使用LINQ的问题吗? – 2010-07-13 13:58:18

2

什么是items?我猜这是ResolutionsRow的列表 - 因此您将需要搜索这个名称/ ID,而不是名称/ ID本身。

如果它们是同一个对象实例,那么就Remove(existingItem)会的工作,但在其他方面(如果他们碰巧有相同.Name,不同对象实例):

items.RemoveAll(item => item.Name == existingItem.Name); 

的方式;你真的需要dynamic吗?没有它,编译器会告诉你这个问题。它不会帮助你,并且很可能会导致很多问题(显式接口实现,lambda等 - 存在的结构不是dynamic的风扇)

+0

dynamic items = Categories = List 类别它们不是相同实例的对象。他们都有.Name,但我仍然没有理解为什么我有错误 – learning 2010-07-13 12:14:13

+0

user281180 - 因为它*不是一个名称列表*。它是*对象*的列表。您正在试图使用接受“ResolutionsRow”的'Remove'方法来移除'string'。这是行不通的。 – 2010-07-13 12:33:58

0

您的items.Contains方法签名期望的类型不同于你提供了什么。看起来你提供了一个字符串而不是ResolutionsRow。

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 } 
0

多久你这样做,并在各列表中有多少个项目?你在做什么通常被认为是“设置操作”(联合,交叉,减号等)。如果对上述任一问题的答案是“很多”,那么你想考虑使用SortedSetHashSet

您当前的实现是O(m * n)(其中m和n是两个列表的大小)。如果你使用散列集合,它是O(n),因为只有第二个集合实际上是迭代的。构建集合也有成本(O(m + n)),但是如果您有足够的对象或者可以将它用于不止一次操作,那么它可以是值得的。