使用一个LINQ查询的结果作为下一个的参数

时间:2013-10-15 22:30:33

标签: linq

我正在尝试使用一个LINQ查询的结果作为LINQ查询的下一部分的参数,但要将其全部保存在一个整体查询中。

例如,我的(不工作)代码看起来像这样

List<Categories> myCats = (from city in myCities
    where city.CityName == myCityName
    select city
    from ids in city.IDs
    where ids != 4
    select ids).ToList();

这可以将结果作为下一个查询的开始以这种方式执行,如果可以的话,我还缺少什么让它工作?

city.IDs是一个int数组

1 个答案:

答案 0 :(得分:1)

除非您实际尝试创建新投影,否则您可以直到最后避免使用select

List<Categories> myCats = (from city in myCities
    where city.CityName == myCityName
    //select city 
    from ids in city.IDs
    where ids != 4
    select ids).ToList();

我个人喜欢将我的疑问分解成碎片:

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();

这种方法有两个主要优点:

  1. 变量名称为您提供自动“文档”,允许其他开发人员查看每次转换的意图。
  2. 调试更容易,因为您可以跨越每个转换并验证您是否获得了所需的结果。
  3. 但是,如果您确实需要按照另一个选择进行操作,则可以使用into关键字将查询链接在一起。

    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();
    
相关问题