开发者

How to compare 2 lists of objects and remove the items that are not common?

开发者 https://www.devze.com 2023-01-06 21:35 出处:网络
I\'ve got 2 generic lists that do not contain the all fields of the same type IList<Category> and List<CategoriesRow>Categories

I've got 2 generic lists that do not contain the all fields of the same type

IList<Category> and List<CategoriesRow>Categories

categoryList = IList<Category>

but both have common fields Name and ID.

I want to compare list Categories with categoryList and find those from categoryList where categoryList[index].ID does not exist in the list of all Categories of ID. For all those that do not exist in Categories, I will have to remove them from CatgoryList.

I had a previous post in which I was given examples of LINQ, but the problem is I h开发者_开发知识库ave to use Dynamic, implying that I am passing categoryList and Categories as Dynamic.

Can anyone give me an example how to go about the above as I have no idea how to do it.


Use the .Except LINQ operator.

Like this:

var uniqueList = list1.Except(list2);

Not sure what you mean by "I have to use Dynamic".

This is a standard LINQ operation available to all types that implement IEnumerable.

Here's a good article on doing it.


let say you have a list1 and list2 like this:

IList<Category> list1 = new List<Category>();
IList<CategoryRow> list2 = new List<CategoryRow>();
//populate lists here....

Now to select from list1 only those items that have a matching Id in list2, you could do

list1 = list1.Where(c => list2.Exists(cr => cr.Id == c.Id)).ToList();

Hope that answers your question

0

精彩评论

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