我正在通过实体数据模型连接和访问的两个表编写一个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);
}
}
答案 0 :(得分: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
值?最后?所有这些的串联?为什么你需要分组呢?
答案 1 :(得分:0)
foreach(var prod in products)
{
prodName += prod.Key.ProductMasterName;
}