linq参数化组由一个Join子句组成

时间:2016-04-04 16:26:47

标签: c# linq

我已经按照这篇文章:LINQ group by property as a parameter制作了一个可参数化的查询,而我现在正试图在group by子句之后做同样的事情,但我无法正确定义组/或访问后面的属性。  这就是我想要实现的目标:

 public Dictionary<string, float?> GetFundingByFilter<TKey>(Expression<Func<Object, TKey>> myGroupingProperty, Filter item)
    {

        int cntToBeSureThatTheQueryExecuteAtLeastOneTime = 0;
        Dictionary<string, float?> countriesAndCount = new Dictionary<string, float?>();
        using (var db = new fintechDbContext())
                {


                    countriesAndCount = (from p in db.companyDBSET
                                join f in db.fundingDBSET on p.Company equals f.Company into d 
                                from t in d.DefaultIfEmpty()
                                select  new  {p, t })
                                .GroupBy(myGroupingProperty)
                                .Select(r => new { Value = r.Key, Sum = r.Sum(d => d == null ? 0 : d.t.Amount) })
                                .OrderByDescending(y=>y.Sum)
                                .ToDictionary(v => v.Value.ToString(), v => v.Sum);



                }
            }
        }
        return countriesAndCount;
    }

但在这种情况下不再可以访问d.t.Amount。

1 个答案:

答案 0 :(得分:1)

Well one thing that you can do is create a custom class (a DTO) to save the projection of your query after do the join:

// Instead of save both instances, you can define this class with only the properties you need from both entities
public class CompanyFundingDTO
{
   public Company Company {get;set;}
   public Funding Funding {get;set;}
}

Then in your method change Object by CompanyFundingDTO:

public Dictionary<string, float?> GetFundingByFilter<TKey>(Expression<Func<CompanyFundingDTO, TKey>> myGroupingProperty, Filter item)
{
       //...
       countriesAndCount = (from p in db.companyDBSET
                            join f in db.fundingDBSET on p.Company equals f.Company into d 
                            from t in d.DefaultIfEmpty()
                            select  new  CompanyFundingDTO{Company=p,Funding= t })//Project this way
                            .GroupBy(myGroupingProperty)
                            .Select(r => new { Value = r.Key, Sum = r.Sum(d => d == null ? 0 : d.Funding.Amount) }
                            .OrderByDescending(y=>y.Sum)
                            .ToDictionary(v => v.Value.ToString(), v => v.Sum);
      //...
}

Now, you can call your method passing the first parameter as I show below:

var result= instance.GetFundingByFilter(ct=>ct.Company.SomeCompanyProperty,...);