使用join语句替换foreach中的查询

时间:2013-07-15 07:16:06

标签: c# linq join

我的数据库中有一个名为Dish的表和一个名为Ingredient的表。我还有另一张名为DishIngredient的桌子,它代表菜肴与其中一种成分或菜肴之间的关系。在DishIngredient中,我还有一个名为“table”的列,它存储菜肴和菜肴,菜肴和配料之间的关系。

这是我的c#代码:

List<int> dish = (from x in db.DishIngredient
                  join y in db.Dish on x.dish_ing_dish equals y.dish_id
                  where x.dish_ing_ing == ing_id && x.table == "Ingredient"
                  select y.dish_id).ToList();

for (int i = 0; i < dish.Count; i++)
{
    int dish_id = dish[i];
    List<int> dish_in_dish = (from x in db.DishIngredient
                              join y in db.Dish on x.dish_ing_dish equals y.dish_id
                              where x.dish_ing_ing == dish_id && x.table == "Dish"
                              select y.dish_id).ToList();
    dish.AddRange(dish_in_dish);
}

dish = dish.Distinct().ToList();

我有一种感觉,我可以通过在Dish和Dish之间加入来获得相同的结果,我只是不知道该怎么做。

可以用Dish和Dish之间的连接重写这​​段代码吗? 我也希望减少时间,什么会更快?

1 个答案:

答案 0 :(得分:0)

我确信你可以通过加入来做到这一点,但我仍然不是那么擅长它们,这会将你的数据库调用减少到2而不是N + 1:

List<int> dish = (from x in db.DishIngredient
                  join y in db.Dish on x.dish_ing_dish equals y.dish_id
                  where x.dish_ing_ing == ing_id && x.table == "Ingredient"
                  select y.dish_id).ToList();

List<int> dish_in_dish = (from x in db.DishIngredient
                              join y in db.Dish on x.dish_ing_dish equals y.dish_id
                              where dish.Contains(x.dish_ing_ing) && x.table == "Dish"
                              select y.dish_id).ToList();

dish = dish.Union(dish_in_dish).ToList();

这可能也有效:

List<int> dish = (from x in db.DishIngredient
    join y in db.Dish on x.dish_ing_dish equals y.dish_id
    where x.dish_ing_ing == ing_id && x.table == "Ingredient"
    select y.dish_id).Union(
        (from x in db.DishIngredient
        join y in db.Dish on x.dish_ing_dish equals y.dish_id
        join a in db.DishIngredient on a.dish_ing_ing equals x.dish_id
        join b in db.Dish on a.dish_ing_dish equals b.dish_id
        where x.dish_ing_ing == ing_id && x.table == "Ingredient"
        and a.table=="Dish"
        select b.dish_id).ToList();