2011-04-18 74 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; 
}