user2357824 user2357824 - 7 months ago 39
ASP.NET (C#) Question

List except and union two list

I have two list.
I need remove items from the first list are not in the second list and add the other elements of the first.

foreach (var product in item.Products)

var newProducts = _catalogService.GetProductBaseItems(x => model.Products.Contains(x.Id))

foreach (var product in newProducts)


You can use Enumerable.Except to find all which are in the first but not in the second. But since your Product class might not override Equals and GetHashCode by comparing the ID's you either have to do it, create a custom IEqualityComparer<Product> or use following approach:

IEnumerable<int> idsInFirstNotSecond = item.Products
    .Select(x => x.Id)
    .Except(newProducts.Select(x => x.Id));
var productsInFirstNotSecond = from p in item.Products
                               join id in idsInFirstNotSecond 
                               on p.Id equals id
                               select p;
List<Product> completeListOfOldAndNew =  productsInFirstNotSecond