开发者

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

开发者 https://www.devze.com 2023-03-09 02:22 出处:网络
Say I have an IList<int> ProductIds that I am passing to a very slow web service.That call would look like this:

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 thing开发者_如何学Pythons but nothing compiles. I'm still new to lambda expressions so hopefully this one is cake.


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


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)

0

精彩评论

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