1

我已经实现了一个可行的解决方案,但是 LINQ 对我来说很重要,我正在努力寻找所需的信息。

这是我所拥有的:

var prodCat = from pc in db.ProductCategories
              where pc.Category == Int32.Parse(CategoriesDropper.SelectedValue)
              select pc;

List<int> productIds = new List<int>();
foreach (var pc in prodCat)
{
    productIds.Add(pc.Product);
}

var products = from p in db.Products
               where productIds.Contains(p.Id)
               select p;

ProductsGridView.DataSource = products;
ProductsGridView.DataBind();

理想情况下,我希望通过一次选择而不是两次选择来获得相同的结果。

4

3 回答 3

2
var products = from pc in db.ProductCategories
               join p in db.Products on pc.Product equals p.Id
               where pc.Category == Int32.Parse(CategoriesDropper.SelectedValue)
               select p;

 ProductsGridView.DataSource = products;
 ProductsGridView.DataBind();

请参阅LINQ - Visual Studio 2010 的 C# 中的联接运算符以供参考。

希望这可以帮助!

于 2013-02-05T20:00:49.937 回答
1

您没有提及您使用的是哪种 LINQ,但假设您在 ProductCategories 和 Products 之间设置了关联,您应该能够执行以下操作:

int Cat = Int32.Parse(CategoriesDropper.SelectedValue);
var products = from pc in db.ProductCategories
               where pc.Category == cat
               from p in pc.Products
               select p;
于 2013-02-05T20:01:37.570 回答
1
var selectedCategory = Int32.Parse(CategoriesDropper.SelectedValue); //Parse the value once
var products = 
    from p in db.Products //foreach product in the database
    join pc in db.ProductCategories
    on pc.Product equals p.Id //where the Ids match
    where pc.Category == selectedCategory  //and with the same category
    select p; //select the product
ProductsGridView.DataSource = products;
ProductsGridView.DataBind();
于 2013-02-05T20:06:52.393 回答