您好我有以下结构:
Table Countries:
- CountryID
- CountryName
Table Records:
- RecordID
- RecordName
- CountryID
此LINQ返回所有国家/地区的列表"以及#34;:
(from i in db.Countries
select new SelectListItem()
{
Text = i.CountryName,
Value = i.CountryID.ToString()
}).ToList();
我想以这样的方式对这个国家列表进行排序:"记录"中最受欢迎的国家/地区。表到顶部列表。怎么做?
答案 0 :(得分:2)
var recordsItem=db.Records.GroupBy(x=> x.CountryID).Select( gr => new{ CID=gr.Key, Count=gr.Count()}).ToList();
var result= (from c in db.Countries
join r in recordsItem on c.CountryID equals r.CID
order by r.Count descending
select new SelectListItem()
{
Text = c.CountryName,
Value = c.CountryID.ToString()
}).ToList();
答案 1 :(得分:2)
您可以尝试这样的事情
(from i in db.Countries
join r in db.Records on i.CountryID equals r.CountryID into rds
orderby rds.Count() descending
select new SelectListItem()
{
Text = i.CountryName,
Value = i.CountryID.ToString()
}).ToList();