LINQ contains between 2 lists

18,363

Solution 1

Following query will return distinct suppliers names which exist in list of names:

suppliers.Where(s => stringlist.Contains(s.CompanyName))
         .Select(s => s.CompanyName) // remove if you need whole supplier object
         .Distinct();

Generated SQL query will look like:

SELECT DISTINCT [t0].[FCompanyName]
FROM [dbo].[Supplier] AS [t0]
WHERE [t0].[CompanyName] IN (@p0, @p1, @p2)

BTW consider to use better names, e.g. companyNames instead of stringlist

Solution 2

You could use Intersect for this (for just matching names):

var suppliersInBothLists = supplierNames
               .Intersect(supplierObjects.Select(s => s.CompanyName));

After your EDIT, for suppliers (not just names):

var suppliers = supplierObjects.Where(s => supplierNames.Contains(s.CompanyName));
Share:
18,363
Crime Master Gogo
Author by

Crime Master Gogo

Updated on June 04, 2022

Comments

  • Crime Master Gogo
    Crime Master Gogo almost 2 years

    I have a string List and a supplier List<supplier>.

    string list contains some searched items and supplier list contains a list of supplier object. Now I need to find all the supplier names that matches with any of the items in the string List<string>.

    this is one of my failed attempts..

    var query = some join with the supplier table.
    query = query.where(k=>stringlist.contains(k.companyname)).select (...).tolist();
    

    any idea how to do that??

    EDIT:

    May be my question is not clear enough...I need to find a list of suppliers(not only names,the whole object) where suppliers names matches with the any items in the string list.

    If I do

    query = query.where(k=>k.companyname.contains("any_string")).select (...).tolist();
    

    it works. but this is not my requirement. My requirement is a list of string not a single string.