Search code examples
c#linqsql-to-linq-conversion

SQL Where in to Linq with DataTable


I'm trying to achieve this in c#

Select a.Name,a.Param
from Customization a
where a.name in (select Name from Standard)

I have try something like this but it still doesn't work.

 merge = dt1.AsEnumerable()
            .Where(r => r.Field<string>("Name")
            .Contains(dt2.Rows.Contains("Name")))
            .CopyToDataTable();

Solution

  • By using the current way we need to get the name list from the second data-table(dt2) for each row in dt1 so I suggest you get the list of names first and then check whether r.Field<string>("Name") contains in the collection. For this, you can use the following code

    var NameCollection = dt2.AsEnumerable().Select(x=> x.Field<string>("Name")).ToList();
    
    merge = dt1.AsEnumerable()
               .Where(r => NameCollection.Contains(r.Field<string>("Name")))
               .CopyToDataTable();