Search code examples
c#entity-frameworklinqselectmany-to-many

LINQ: Select values from two columns based on one of the column value


I have a table like this:

Column A Column B
Peter Apple
Peter Orange
Peter Melon
John Apple
John Potato
John Melon
Suzane Kiwi
Suzane Cucumber
Suzane Orange

I need to select values from Column A and values from Column B where Column B contains value Orange, so the resulting table should look like:

Column A Column B
Peter Apple
Peter Orange
Peter Melon
Suzane Kiwi
Suzane Cucumber
Suzane Orange

Is this possible preferably in LINQ or Entity Framework please?

I've tried to find similar question, but have not succeeded so far


Solution

  • Start by selecting all values of ColumnA where ColumnB matches Orange, e.g.

    var as = (from ab in db.Table where ab.ColumnB == 'Orange' select ab.ColumnA);

    Then select all records where column A has a value in that "list", e.g.

    var results = (from ab in db.Table where as.Contains(ab.A) select ab).ToList();

    Doesn't really matter that there are two queries as Linq2Sql or EF should combine them into one Sql query.