匿名类型的写作组



我正在两个表上写一个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);
        }
    }

一个问题是您无缘无故地使用了查询延续。注意,这并不妨碍你使用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值是多少?最后一个吗?所有这些的串联?你为什么需要分组呢?

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

相关内容

  • 没有找到相关文章

最新更新