Linq查询平均值

时间:2016-03-02 12:28:44

标签: c# linq linq-to-sql

我有3张桌子:

tblCompany : Id, Name, Location 
tblRating  : Id, CompanyId, Rate 
tblImages  : Id, CompanyId, ImagePath

我有一个班级

public class Company
{
    public string Id { get; set; }
    public string CompanyName { get; set; }
    public string Location { get; set; }
    public string AverageRate { get; set; }
    public List<string> ImagePath { get; set; }
}

我想要一个LINQ查询来生成一个匹配Company类的结果。

我写了这个查询,但它不起作用

        List<Company>  result = null;

        using (DataContext dc = new DataContext())
        {
            result = (from a in dc.GetTable<tblCompany>()
                      join b in dc.GetTable<tblRating>()
                      on a.Id equals b.CompanyId
                      join c in dc.GetTable<tblImages>()
                      on a.Id equals c.CompanyId

                      select new SearchResult
                      {
                          CompanyName = a.Company,
                          Location = a.Location,
                          AverageRate = b.Rate.Average(),
                          ImagePath = c.ImagePath.ToList()

                      }).ToList<Company>();
        }

2 个答案:

答案 0 :(得分:1)

编辑整个查询:

(我很抱歉,我还没办法测试这个查询)

您可以使用let clause代替联接:

var result = (from c in dc.GetTable<tblCompany>()

              let r = (from re in dc.GetTable<tblRating>()
                       where re.CompanyId == c.Id && re.Rate != null
                       select re.Rate)

              let i = (from im in dc.GetTable<tblImages>()
                       where im.CompanyId == c.Id
                       select im.ImagePath)

              select new SearchResult
              {
                  CompanyName = c.Name,
                  Location = c.Location,
                  AverageRate = r.Average(),
                  ImagePath = i.ToList()
              }).ToList<Company>();

答案 1 :(得分:0)

试试这个 -

result = (from a in dc.GetTable<tblCompany>()
                      join b in dc.GetTable<tblRating>()
                      on a.Id equals b.CompanyId
                      join c in dc.GetTable<tblImages>()
                      on a.Id equals c.CompanyId
                      group new { b.Rate, c.ImagePath}
                      by new { a.Id, a.Location,a.Name} into groupList
                      select new Company
                      {
                          CompanyName = groupList.Key.Name,
                          Location = groupList.Key.Location,
                          AverageRate = groupList.Average(a=>a.Rate),
                          ImagePath = groupList.Select(i=>i.ImagePath).ToList()

                      }).ToList<Company>();