1

I've implemented a solution that works, but LINQ is a something nre for me and I am struggling to find the required information.

Here is what I have:

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

Ideally I would like to achieve the same result with a single select rather than two.

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

See LINQ - Join Operators in C# for Visual Studio 2010 for reference.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

1

You don't mention which flavor of LINQ you are using, but assuming you have the associations set between ProductCategories and Products, you should be able to do something like this:

int Cat = Int32.Parse(CategoriesDropper.SelectedValue);
var products = from pc in db.ProductCategories
               where pc.Category == cat
               from p in pc.Products
               select p;

3 Comments

does this end up as a single select or will it execute two selects from the sql db?
Because of the composable nature and deferred execution, it will be one query which is generated when .GetEnumerator is called in the data binding.
Join is important for associating values that aren't naturally associated as part of an object graph. I often find join abused in LINQ to do object graph traversal because people think in SQL rather than OOP when working with data. Typically, both syntaxes achieve the same resulting SQL
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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.