MVC2 Grouping and displaying products by date
Good morning Stack Overflow, I just passed my view a list of products for the last 90 days sorted by date and need to display it in an efficient way that will group the products by date. Linq-To-Sql doesn't understand a lot of the date comparison functions, so I'm kinda lost as to what to do here.
What I would like to do is contain each group of products with the same date inside of a div with a title like "T开发者_运维知识库oday", "Yesterday" or "Last 30 Days". Can anybody assist?
So, as i understand you need groups like history groups in skype:
Show messages from: Yesterday * 7 days * 30 days .. etc.
Suppose you have class Product with Date and some others fields, like this:
public class Product
{
public DateTime Date { get; set; }
public string ProductName { get; set; }
}
Than you can create some helper class like this:
public enum ProductGroupEnum
{
Today = 0,
Yesterday = 1,
Last30Days = 30
}
public static class ProductsHelper
{
public static List<Product> GetProductsGroup(ProductGroupEnum group, IEnumerable<Product> products)
{
var daysCount = (int)group;
return products.Where(x => DateTime.Now.Date - x.Date.Date <= new TimeSpan(daysCount, 0, 0, 0)).ToList();
}
}
Instead of enum you can pass date i think, like DateTime.Now.AddDays(-1) for example. Because if you want 'last 3 month group' it is incorrect to use 90 days.
And a final example of code:
var products = new List<Product>()
{
new Product() {Date = DateTime.Now.AddMinutes(-30), ProductName = "TodayProduct"},
new Product() {Date = DateTime.Now.AddDays(-1), ProductName = "YesteradayProduct"},
new Product() {Date = DateTime.Now.AddDays(-25), ProductName = "LastMonthProduct"}
};
var todayProducts = ProductsHelper.GetProductsGroup(ProductGroupEnum.Today, products);
var yesterdayProducts = ProductsHelper.GetProductsGroup(ProductGroupEnum.Yesterday, products);
So 'todayProducts' will contain only first one products, but 'yesterdayProducts' will containt first two products(means products from yesterday to today).
Also you can easily use above 'ProductsHelper' helper method in 'view' for products filtering according yous needs.
Hope this help.
精彩评论