简体   繁体   中英

linq to sql sub-select

I have two tables that represent say a Mixture and the components of the Mixture. The table layouts are like:

Mixture table:
MixtureID uniqueidentifier
MixtureDescription varchar(50)

Components table:
ComponentID uniqueidentifier
MixtureID uniqueidentifier (FK to previous table)
ComponentName varchar(50)
ComponentRatioPercentage int

Now, what I want to do is take a list of component names inputted from the user and find the ID's of any mixes that contain all of those components.

In SQL I could so something like:

select distinct MixtureID 
from Mixture Mixture 
where exists (select ComponentName
       from Components Components1
       where Components1.MixtureID = Mixture.MixtureID and
             Components1.ComponentDescription = 'SomeComponentName')
      and exists (select ComponentName
       from Components2 
       where Components2.MixtureID = Mixture.MixtureID and
             Components2.ComponentDescription = 'SomeOtherComponentName')
      and exists....

etc, adding a sub-select for each component.

How would I do something like this in linq to sql? The number of components to look for would not be known in advance, until the user is done with input, though there would be a max of 10. Thanks in advance!

var components = new string[] {"SomeComponentName", "SomeOtherComponentName"};
var query = Mixtures.AsQueryable();
foreach (var component in components)
{
    var tmpComponent = component;
    query = query.Where(m => m.Components
                                  .Any(c => t.ComponentDescription == tmpComponent)
                           );
}

var mixturesIds = query.Select(m=>m.MixtureId).Distinct();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM