我有两个表动物和马戏团,它们具有多对多关系,从而产生了关联类 Contract ,我有一个品种类,该类通过一对多关系与动物相关联。 如何找到具有最多马戏团动物数量的品种。
我已经尝试过了:
var req = from Animal A in Contract
group A by A.Breed into g
select max { g.Key, Count = g.Count() };
但是它不起作用 我的意思是,例如,我们有:
**Animal_FK** **Circus_FK** **Salary** **Contract_ date**
---------- ---------- ------------ -------------------
S3 C10 3000 2015-12-12
S1 C12 5000 2010-10-17
D2 C18 4000 2016-02-22
B4 C85 3500 2018-09-30
S2 C6 2700 2014-05-10
Animal_key Name
------------- -------------
S1 Python
S2 Cobra
S3 Boa
D1 Bulldog
D2 Labrador
B1 Owl
B2 Dove
Beer_Key Name Description
---------- --------- ----------------
S Snake reptile
D Dog pet
B Birds flying animals
查询结果将为蛇
答案 0 :(得分:0)
我假设这里有一些POCO。我不会提供诸如薪水等其他详细信息,而只是最低限度。
public class Breed
{
public string Name { get; set; }
}
public class Animal
{
public string Name { get; set; }
public Breed Breed { get; set; }
}
public class Circus
{
public string Name { get; set; }
}
public class Contract
{
public Animal Performer { get; set; }
public Circus Venue { get; set; }
}
然后设置一些数据,以表示您上面的信息。
var breeds = new[]
{
new Breed {Name = "Snake"},
new Breed {Name = "Dog"},
new Breed {Name = "Bird"}
};
var animals = new[]
{
new Animal{Name="Boa", Breed = breeds[0]}, // 0
new Animal{Name="Python", Breed = breeds[0]}, // 1
new Animal{Name="Cobra", Breed = breeds[0]}, // 2
new Animal{Name="Bulldog", Breed = breeds[1]}, // 3
new Animal{Name="Labrador", Breed = breeds[1]},// 4
new Animal{Name="Dove", Breed = breeds[1]}, // 5
new Animal{Name="Owl", Breed = breeds[2]}, // 6
};
var circuses = new[]
{
new Circus {Name = "C1"},
new Circus {Name = "C2"},
new Circus {Name = "C3"},
new Circus {Name = "C4"},
new Circus {Name = "C5"},
};
var contracts = new[]
{
new Contract {Performer = animals[0], Venue = circuses[0]},
new Contract {Performer = animals[1], Venue = circuses[1]},
new Contract {Performer = animals[2], Venue = circuses[2]},
new Contract {Performer = animals[4], Venue = circuses[3]},
new Contract {Performer = animals[6], Venue = circuses[4]},
};
然后这就是您获得最具代表性的品种的方法:
var mostRepresentedBreed = (
from contract in contracts
group contract by contract.Animal.Breed
into contractsByBreed
orderby contractsByBreed.Count() descending
select contractsByBreed.Key
).FirstOrDefault();
var theWinnerIs = mostRepresentedBreed.Name;
希望这会有所帮助。 布雷特。