Linq and Lambda Expression get count for group and distinct
I've been trying to get the "Count" for my "Value" field in my query e开发者_如何学Goxpression. In my code it suppose to create a list of checkboxes and beside the checkboxes is a count of how many items are in the list(checkbox).
Could someone show me how to get the count for the items of my field Value this is a checbox filtering system I'm making.I've just started learning linq and lambda exressions.
Code in C# ASP.NET
var dept = Page.RouteData.Values["department"];
var department = (from d in db.Departments where d.Name.Replace(" ", "-") == dept select new {d.Id, d.Name}).FirstOrDefault();
var query = (from p in db.Products
join f in db.ProductFilters on p.Id equals f.ProductId into filters
from x in filters.Where(x => x.Product.DepartmentId == department.Id)
select new { x.Id, x.Name, x.Value }).ToList();
var brand = query.Where(x => x.Name == "Brand").OrderBy(x => x.Value);
var price = query.Where(x => x.Name == "Price").OrderBy(x => x.Value);
var brandAndPrice = brand.Concat(price);
var labelBrandAndPrice = (from f in brandAndPrice select new { f.Name }).Distinct().OrderBy(x => x.Name);
//var otherFilters = query.Except(brandAndPrice);
StringBuilder sb = new StringBuilder();
sb.Append("<div class=\"Filters\">");
foreach (var label in labelBrandAndPrice)
{
sb.Append("<span>" + label.Name + "</span><br />");
sb.Append("<div class=\"ProdFilters\">");
// Below is where I wanted to do distinct expression and groupby but it didn't work
var BrandPriceCollection = brandAndPrice.Where(x => x.Name == label.Name).Distinct().ToList();
foreach (var bp in BrandPriceCollection)
{
//Here i want to write out the count for the field Value
sb.Append("<input type=\"checkbox\" id=\"" + bp.Value + "\" /><span>" + bp.Value + "(" + "Count" + ")" + "</span><br />");
}
sb.Append("</div>");
}
sb.Append("</div>");
var BrandPriceCollection = brandAndPrice.Where(x => x.Name == label.Name).Distinct().ToList();
var groupings = BrandPriceCollection.GroupBy(x => x.Value);
foreach (var g in groupings)
{
//Here i want to write out the count for the field Value
sb.Append("<input type=\"checkbox\" id=\"" + g.Key + "\" /><span>" + g.Key + "(" + g.Count() + ")" + "</span><br />");
}
GroupBy
returns your data in the structure like Dictionary, with value you are grouping on in Key
property and the collection of elements inside, so you can just Count()
it. Note that groupings
is the collection of collections now.
精彩评论