I have a controller that calls a method in my repository that runs a linq to entities query to get a list of products for my application. I'd like to add the ability for a user to filter the results (something like standard price high to low, low to high, etc etc).
So I'm thinking I need to dynamically populate my orderby in the repository, but am having trouble with this. I'm shaky on generics in c#, so please bear with me.
Controller
model.Products = ProdRepo.GetProducts ((int)CategoryId, 0, 8);
Model
//get a list of the products
public List<ProductModel> GetProducts (int CategoryId, int Start, int End)
{
List<ProductModel> Products = new List<ProductModel>();
var products = (from p in db.products select p).AsEnumerable().OrderByWithDirection(x=> x.date_added, true).Where( x => x.category_id == CategoryId).Where((row, index) => index >= Start && index < End).ToList();
if (products.Count > 0)
{
foreach (var item in products)
{
ProductModel model = new ProductModel();
model.CategoryId = item.category_id;
model.Description = item.description;
model.Id = item.id;
model.Product = item.product1;
model.DateAdded = item.date_added;
model.Image = item.image;
model.Price = item.price;
Products.Add(model);
}
}
}
So I'm thinking I need to pass a Func<TSource, TKey> from my controller, but I having trouble piecing together how to accomplish that. Any help would be greatly appreciated.