Reputation: 1581
I'm trying to use the result of one LINQ query to be the parameter for the next part of a LINQ query, but to keep it all within one overall query.
For example, my (not-working) code looks like this
List<Categories> myCats = (from city in myCities
where city.CityName == myCityName
select city
from ids in city.IDs
where ids != 4
select ids).ToList();
Can this feed the result to be the be start of the next query be performed in this fashion and if it can, what am I missing to get this to work?
city.IDs is an int array
Upvotes: 1
Views: 125
Reputation: 156634
Unless you're actually trying to create a new projection, you can simply avoid using a select
until the end.
List<Categories> myCats = (from city in myCities
where city.CityName == myCityName
//select city
from ids in city.IDs
where ids != 4
select ids).ToList();
I personally like breaking up my queries into pieces:
var matchingCities = from city in myCities
where city.CityName == myCityName
select city;
var matchingCityIds = (from city in matchingCities
from id in city.IDs
select id).ToList();
This approach has two main advantages:
If you really do need to follow one select by another, though, you can use the into
keyword to chain the queries together.
List<Categories> myCats = (from city in myCities
where city.CityName == myCityName
// Not typically recommended
select city.IDs into cityIDs
from id in cityIDs
where id != 4
select id).ToList();
Upvotes: 1