开发者

Filtering a list based on another list - LINQ

开发者 https://www.devze.com 2023-04-09 15:49 出处:网络
I have two IEnumerable lists. I want to populate values into the second list based upon the results in the first.

I have two IEnumerable lists.

I want to populate values into the second list based upon the results in the first.

The first IEnumerable list is populated like开发者_如何学编程 this:

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

I have a function to get all attributes. Now I want to get another list which contains all other attributes (ie, the items not present in selectedList). I tried this:

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

But its not filtering. I am getting all attributes... Any ideas?


Make sure your SelectListItem class implements IEquatable<SelectListItem> so the Contains() method has a proper means for determining equality of instances.


I think this will help you

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);
}

Result

Numbers in first array but not second array: 0 2 4 6 9


GetAllAttributes() will probably get you a new round of objects, they will not be the same as those returned by GetAttributesByCategoryID(...). You need to compare something better than object references.

You can implement System.IEquatable<T> to change the default comparer.

0

精彩评论

暂无评论...
验证码 换一张
取 消