user623647
user623647

Reputation: 133

c# lambda expression to remove items from a list based on given conditions in a different list

Say I have an IList<int> ProductIds that I am passing to a very slow web service. That call would look like this:

var WebServiceResponse = client.SomeCall(ProductIds);

The list of ints will contain all product IDs for a given page.

I have another list, say IList<Product> where Product contains an int ProductId member property. I want to call my web service, but before doing so I want to remove every item from ProductIds that has a Product in my other list with a matching ProductId. Is there a one liner that can do this for me or do I have to run a loop? I've tried all sorts of things but nothing compiles. I'm still new to lambda expressions so hopefully this one is cake.

Upvotes: 4

Views: 6353

Answers (2)

AD.Net
AD.Net

Reputation: 13399

var excluded = ListA.Where(p=>!ListB.Contains(pb=>pb.Id == p.Id));

Could be a little bit different if ListB is only Ids, then it'll be just !ListB.Contains(p.Id)

Upvotes: 0

BFree
BFree

Reputation: 103740

var list = new List<Product>(); //or wherever you get it from
var otherIDs = list.Select(p => p.ProductId);
var WebServiceResponse = client.SomeCall(ProductIds.Where(i => !otherIDs.Contains(i)); 

If your web service takes a List or IList specifically, you'll need to add a ToList at the end:

var WebServiceResponse = client.SomeCall(ProductIds.Where(i => !otherIDs.Contains(i).ToList()); 

Upvotes: 4

Related Questions