Writing Group By on Anonymous Types

我只是一个虾纸丫 提交于 2019-12-07 07:14:52

问题


I am writting a group by clause on two tables which are joined and being accessed via Entity Data Model. I am not able to iterate over the anonymous type, can somebody help me out.

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

回答1:


One problem is that you've used a query continuation for no reason. That still shouldn't have prevented you from using the Key property, mind you. Try this as a slightly cleaner approach:

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.
}

As for what you set your prodName variable to - it's unclear exactly what you want. The first ProductName value? The last? A concatenation of all of them? Why do you need a grouping at all?




回答2:


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


来源:https://stackoverflow.com/questions/5703593/writing-group-by-on-anonymous-types

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!