我已经实现了一个有效的解决方案,但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();
理想情况下,我希望通过一次选择而不是两次选择来获得相同的结果。
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();
请参阅C#for Visual Studio 2010中的LINQ-Join运算符以获取参考。
希望这能有所帮助!
您没有提到您正在使用哪种风格的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;
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();