Compare two lists and return common entries
I have a list of vendors. I also have a list of vendor ids.
public List<SAP_Vendor> Vendors { 开发者_如何学编程get; set; }
public List<string> SubcontractVendorIDs { get; set; }
I want to return a List<SAP_Vendor>
of the vendors whose ids are in the SubcontractVendorIDs list.
List<SAP_Vendor> SubcontractVendors = Vendors.Select(??).ToList();
or
List<SAP_Vendor> SubcontractVendors = Vendors.Where(??).ToList();
Use the Contains()
method in the Where()
predicate:
List<SAP_Vendor> SubcontractVendors = Vendors.Where(v=> SubcontractVendorIDs.Contains(v.VendorID)).ToList();
You can perform an inner join:
var query = from vendor in Vendors
join id in SubcontractVendorIDs on vendor.ID equals id
select vendor;
List<SAP_Vendor> subcontractVendors = query.ToList();
List<SAP_Vendor> SubcontractVendors = Vendors.Where(v => SubcontractVendorIDs.Contains(v.Id)).ToList();
Do you need to be using Lists? With LINQ, it's usually best to pass around IEnumerables and only convert to a list when you actually need the data.
As for your actual question, just use the Contains
method.
Vendors.Where(v => SubcontractVendorIDs.Contains(v.Id));
List<SAP_Vendor> SubcontractVendors = Vendors.Where(x => SubcontractVendorIDs.Any(y => x == y)).ToList();
One of several ways to do this... Would be faster with a Dictionary or a sorted list
精彩评论