Writing Group By on Anonymous Types

2019-05-05 18:42发布

问题:

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