2011-04-18 76 views
4

我正在通過實體數據模型連接和訪問的兩個表上寫入group by子句。我無法迭代匿名類型,有人可以幫我解決問題。在匿名類型上編寫分組

public string GetProductNameByProductId(int productId) 
    { 
     string prodName=string.Empty;   
     using (VODConnection vodObjectContext = new VODConnection()) 
     { 

      var products = from bp in vodObjectContext.BFProducts 
              join bpf in vodObjectContext.BFProductMasters on bp.ProductMasterId equals bpf.ProductMasterId 
              where bp.ProductId == productId 
          group bp by new { ProductId = bp.ProductId, ProductName = bp.ProductName, ProductMasterName=bpf.ProductMasterName} into newInfo 
          select newInfo; 

//Want to iterate over products or in fact need to get all the results. How can I do that? Want productmastername property to be set in prodName variable by iterating 

      return (prodName); 
     } 
    } 

回答

7

一個問題是,你使用的查詢延續無緣無故。這仍然不應該阻止你使用Key財產,請注意。試試這個作爲一個稍微更簡潔的方法:

var products = from bp in vodObjectContext.BFProducts 
       join bpf in vodObjectContext.BFProductMasters 
       on bp.ProductMasterId equals bpf.ProductMasterId 
       where bp.ProductId == productId 
       group bp by new { bp.ProductId, 
           bp.ProductName, 
           bpf.ProductMasterName}; 

foreach (var group in products) 
{ 
    var key = group.Key; 
    // Can now use key.ProductName, key.ProductMasterName etc. 
} 

至於你設置你的prodName變量 - 目前還不清楚你想要什麼。第一個ProductName的值?最後?他們所有的連接?爲什麼你需要一個分組?

+0

謝謝Jon。我是LINQ的新手,並且正在嘗試使用一些基本教程來做這些事情,所以一個糟糕的代碼。這個group.key非常有幫助。萬分感謝。 – 2011-04-18 13:46:17

0
foreach(var prod in products) 
{ 
    prodName += prod.Key.ProductMasterName; 
}