如何比较2个列表值?

时间:2010-07-13 11:48:45

标签: c#

我有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))
                   {

                   }
                }

6 个答案:

答案 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)

您经常这样做,以及每个列表中有多少项?你正在做的通常被认为是“设置操作”(联合,交集,减号等)。如果前面任一问题的答案“很多”,那么您要考虑使用SortedSetHashSet

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