Simple LINQ equiv of GROUP BY

  • Thread starter Thread starter Justin Dutoit
  • Start date Start date
J

Justin Dutoit

Hey folks. Using LINQ to entities syntax, what is the equivalent of the old
t-sql:

SELECT CategoryPrimary
FROM Products
GROUP BY CategoryPrimary

? My incomplete code is below. Thanks for helping.

public List<string> PrimaryCategories()
{
using (Quickshop35sp1 QS35sp1Entities = new Quickshop35sp1())
{
List<string> primaries = new List<string>();
ObjectQuery<Products> products = QS35sp1Entities.ProductsSet;

IQueryable<Products> productsQuery =
from prod in products
group prod by
prod.CategoryPrimary into grp
select ?; //** <<< here

foreach (Products primary in productsQuery)
{
primaries.Add(primary.CategoryPrimary);
}

return primaries;
}

}
 
Justin said:
Hey folks. Using LINQ to entities syntax, what is the equivalent of the old
t-sql:

SELECT CategoryPrimary
FROM Products
GROUP BY CategoryPrimary

? My incomplete code is below. Thanks for helping.

public List<string> PrimaryCategories()
{
using (Quickshop35sp1 QS35sp1Entities = new Quickshop35sp1())
{
List<string> primaries = new List<string>();
ObjectQuery<Products> products = QS35sp1Entities.ProductsSet;

IQueryable<Products> productsQuery =
from prod in products
group prod by
prod.CategoryPrimary into grp
select ?; //** <<< here

Try
List<string> primaries =
(from prod in products
group prod by prod.CategoryPrimary into g
select g.Key).ToList();
 
Back
Top