Avatar ·

How to get elements from one list that are not in another list using LINQ in C#?

Hello everyone! I'm a beginner C# developer, and I encountered a problem while working with collections. There are two lists of objects of the same type. Let's say I have a Product class with Id and Name fields. The first list (listA) contains all products from the database, and the second (listB) is a list of products that the user has already selected for an order. I need to get a third list (listC) that will contain only those products from listA that are not in listB. I tried using a foreach loop and checking Contains, but it looks cumbersome and ugly. Plus, when the lists are large, such code runs slowly. I've heard that LINQ allows you to do such things elegantly and quickly. Please advise how to correctly write a query to get elements that are missing from the second list? It's important that the comparison is pro