我如何只是LINQ Join()链接两个IQueryables? [英] How do I just LINQ Join() to link two IQueryables?

查看:1159
本文介绍了我如何只是LINQ Join()链接两个IQueryables?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个IQueryables:

I have two IQueryables:

成分:

IngId
Description

AvailableIngredient:

IngId


$ b b

我已经有一个IQueryable的成分:

I already have an IQueryable for Ingredient:

var ingQuery = from i in context.Ingredients
               select i;

如何添加一个联接到他所以它筛选 AvailableIngredient (即内连接)?我知道如何做,如果我不得不加入所有的时间,即从...加入context.Available ...等),但加入是有条件的,所以我需要使用其他语法:

How can I add a join to his so it filters by AvailableIngredient (i.e. an Inner Join)? I know how to do it if I had to join all the time, i.e. from... join context.Available... etc), but the Join is conditional, so I need to use the other syntax:

if (filterByAvailable)
{
   IQueryable<Available> availableQuery = GetAvailableIngredientQuery(context);
   ingQuery = ingQuery.Join(...); // Can I use this to join to the query?
}

这可能不是正确的方法,所以这是我想做的:

This may not be the right method, so this is what I want to do:


  • GetAvailableIngredientQuery返回
    可用成分查询,即
    3000 of 6000(但不会
    枚举结果,因为
    作为IQueryable从EF返回)

  • 将availableQuery加入到ingQuery中,因此两个查询之间有一个内部联接

EDIT:

目前使用(非常快),但是它意味着重复的代码:

This is the code I'm currently using (very fast), but it means duplicated code:

IQueryable<Ingredient> query;
if (filterByAvailable)
{
    IQueryable<Available> availableQuery = GetAvailableIngredientQuery(context);
    query = from item in context.Ingredients
               // Quite a few `where` clauses and stuff
            join t in availableQuery on item.IngId equals t.IngId
            select item;
}
else
{ 
    query = from item in context.Ingredients
               // The SAME `where` clauses and stuff as above
            select item;
}


推荐答案

使用第一个查询

IQueryable<Ingredient> query = from item in context.Ingredients
                             // Quite a few `where` clauses and stuff
                               select item;

if (filterByAvailable)
{
    IQueryable<Available> availableQuery = GetAvailableIngredientQuery(context);
    query = from item in query
            join t in availableQuery on item.IngId equals t.IngId
            select item;
}

这篇关于我如何只是LINQ Join()链接两个IQueryables?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆