1

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

4

1 回答 1

1

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:

  1. The variable names give you automatic "documentation", allowing other developers to see what the intent of each transformation is.
  2. It's easier to debug because you can step over each transformation and verify that you got the results you wanted.

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();
于 2013-10-15T22:33:15.983 回答