Linq通过在另一个列表中出现外键来查询订单列表

时间:2014-05-07 12:59:24

标签: c# asp.net linq

我有两个课程,简介和下载。下载具有映射到Profile中的ID的外键ProfileID。 “下载”中的每一行代表连接配置文件的一次下载。

我在制作一个linq查询时遇到问题,该查询提取了一个已下载多少次的有序配置文件列表。

编辑: 这是我到目前为止在函数中所拥有的。

    IndexViewModel model = new IndexViewModel();
    model.NewSubtitles = (from Profile in _ProfileRepo.GetAll()
                      orderby Profile.ID descending
                      select Profile).Take(5).ToList();

    // This doesn't work:
    // model.TopSubtitles = (from n in _ProfileRepo.GetAll()
    //                       join d in _DownloadRepo.GetAll() on n.ID equals d.ProfileID into c
    //                       group c by c.ProfileID into g
    //                       orderby g.Count() descending
    //                       select n).Take(5).ToList();

        return View(model);

3 个答案:

答案 0 :(得分:1)

试试这个:

     model.NewSubtitles = (from Profile in _ProfileRepo.GetAll()
                  join downloads in _DownloadRepo.GetAll() on Profile.UserId equals downloads.UserId
                 group downloads by Profile into p
                  orderby p.Count() descending
                  select new {p.Key.UserId , p.Key.UserName , p.Count()).Take(5).ToList();

答案 1 :(得分:0)

你有没有试过像:

from d in Downloads
orderby d.Profiles.Count()
...

答案 2 :(得分:0)

应该做你想做的事:

model.TopSubtitles =  (from p in _ProfileRepo.GetAll()
                      join d in _DownloadRepo.GetAll() on p.ID equals d.ProfileId
                      group d by p into g
                      orderby g.Count() descending
                      select g.Key).Take(5).ToList();

并且对于LINQ语法challenged:

model.TopSubtitles = _ProfileRepo.GetAll()
  .Join(_DownloadRepo.GetAll(), p => p.ID, d => d.ProfileId, (p, d) => new { Profile = p, Download = d })
  .GroupBy(x => x.Profile)
  .OrderByDescending(g => g.Count())
  .Select (g => g.Key)
  .Take(5)
  .ToList();