2011-06-19 2 views
1

私はクエリ式の "Value"フィールドの "Count"を取得しようとしています。私のコードでは、チェックボックスのリストを作成すると仮定し、チェックボックスの隣には、リスト内のアイテムの数(チェックボックス)が入ります。LinqとLambda式がグループと別名を取得する

私のフィールドのアイテムの数を得る方法を教えてもらえますかこれは私が作っているChecboxフィルタリングシステムです。私はちょうどLINQとラムダのエクスプレッションを学び始めました。

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

答えて

2
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あなたはKeyプロパティでのグループ化されている値と内部の要素のコレクションで、辞書のような構造でデータを返すので、あなただけのことができますCount()です。 groupingsは今コレクションのコレクションです。

+0

私はそれを前にして、あなたに戻ってきます – ONYX

+0

私はそれを試して、それは働いた私は今日何か新しいことを学んだことはありがとうヒープだと思う。 – ONYX

関連する問題