假设我有两组;糖果和地区。对于每个糖果,我都有一个糖果在某个区域(CandyRegion)中被称为的一对多名称。从最高计数组中选择值
我想创建一个只有一个CandyRegion.Name被选中的Candy对象列表。所选CandyRegion.Name由最受欢迎的地区(该地区可用的糖果数量最多)决定。
什么是一种合适的方式来执行查询来找到最流行的地区?我到目前为止:
context.Candys
.Select(c => c.CandyRegions
.OrderByDescending(cr =>
/*
* Order CandyRegion by Candy.CandyRegion.Count outside
* the context of c?
*/
context.CandyRegions.Count(cr2 => cr2.RegionId == cr.RegionId)
)
.FirstOrDefault()
)
.ToList();
我有一种感觉,上述查询的性能将是一个问题。
编辑:类
public class Candy
{
public int Id { get; set; }
...
public virtual List<CandyRegion> CandyRegions { get; set; }
}
public class Region
{
public int Id { get; set; }
...
public virtual List<CandyRegion> CandyRegions { get; set; }
}
public class CandyRegion
{
public int Id { get; set; }
public string Name { get; set; }
...
public int RegionId { get; set; }
public virtual Region Region { get; set; }
public int CandyId { get; set; }
public virtual Candy Candy { get; set; }
}
你提到你有两套。通过你的代码片断,糖果对象包含一系列糖果区域,是否正确?如果是这样的话,你在技术上有一个包含一个集合的对象,而不是两个单独的集合,这意味着你需要某种连接子句。 – 2015-02-06 04:28:53
@JamesShaw是的,CandyRegion是糖果和地区的集合。地区将是第二套。糖果和地区加入CandyRegion。 – 2015-02-06 04:42:13
@DamonPollard我想你应该也发布有问题的糖果和地区类!它会造成混淆。 – 2015-02-06 04:54:49