基于另一个列表过滤列表 - LINQ

时间:2011-10-01 18:33:07

标签: c# linq asp.net-mvc-2

我有两个IEnumerable列表。

我想根据第一个中的结果将值填充到第二个列表中。

第一个IEnumerable列表填充如下:

IEnumerable<SelectListItem> selectedList =
CategoryServices.GetAttributesByCategoryID(categoryID); // it returns selected attributes for a particular category

我有一个获取所有属性的函数。现在我想获得另一个包含所有其他属性的列表(即,selectedList中不存在的项)。我试过这个:

IEnumerable<SelectListItem> available =
CategoryServices.GetAllAttributes().Where(a => !selectedList.Contains(a));

但它不是过滤。我得到了所有属性......任何想法?

3 个答案:

答案 0 :(得分:2)

确保您的SelectListItem类实现IEquatable<SelectListItem>,以便Contains()方法具有确定实例相等性的正确方法。

答案 1 :(得分:2)

我认为这会对你有帮助

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);

Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers)
{
    Console.WriteLine(n);
}

结果

第一个数组中的数字但不是第二个数组: 0 2 4 6 9

答案 2 :(得分:0)

GetAllAttributes()可能会为您提供新一轮的对象,它们与GetAttributesByCategoryID(...)返回的对象不同。你需要比对象引用更好地比较一些东西。

您可以实施System.IEquatable<T>来更改default comparer

相关问题