我只想要每组最大计数的记录。必须根据具有最大记录数的选区对结果进行分组。这是代码。
protected void Page_Load(object sender, EventArgs e)
{
var query1 = from m in db.Votes
group m by m.CandidateID
into g
let w= g.ToArray().Count()
orderby w descending
select new {CFN=
(from a in db.Persons where a.PersonID==((from j in db.Candidates
from u in db.Persons
where j.PersonID==u.PersonID && j.CandidateID==g.Key
select u.PersonID).Single())select a.PersonFirstName ).Single(),
CMN =
(from a in db.Persons
where a.PersonID == ((from j in db.Candidates
from u in db.Persons
where j.PersonID == u.PersonID && j.CandidateID == g.Key
select u.PersonID).Single())
select a.PersonMiddleName).Single(),
CLN =
(from a in db.Persons
where a.PersonID == ((from j in db.Candidates
from u in db.Persons
where j.PersonID == u.PersonID && j.CandidateID == g.Key
select u.PersonID).Single())
select a.PersonLastName).Single(),
PName=
(from b in db.Parties
where b.PartyID==((from c in db.Candidates
from d in db.Parties
where c.PartyID==d.PartyID && c.CandidateID==g.Key
select d.PartyID).Single())
select b.Name).Single(),
ConName=
(from d in db.Candidates
where d.CandidateID==g.Key
select d.ConstituencyName).Single()
,VC=w};
foreach (var pair in query1)
{
TableRow row = new TableRow();
TableCell cell1 = new TableCell();
cell1.Style.Value = "text-align:center";
cell1.Text = pair.CFN+" "+pair.CMN+" "+pair.CLN;
TableCell cell2 = new TableCell();
cell2.Style.Value = "text-align:center";
cell2.Text = pair.PName;
TableCell cell3 = new TableCell();
cell3.Style.Value = "text-align:center";
cell3.Text = pair.VC.ToString();
TableCell cell4 = new TableCell();
cell4.Style.Value = "text-align:center";
cell4.Text=pair.ConName;
row.Cells.Add(cell1);
row.Cells.Add(cell2);
row.Cells.Add(cell3);
row.Cells.Add(cell4);
table1.Rows.Add(row);
}
}
我收到以下输出
Candidate Name Party Name Votes Constituency
C1 P1 12 C1
C2 P2 5 C2
C3 P1 3 C1
我想要关注输出
Candidate Name Party Name Votes Constituency
C1 P1 12 C1
C2 P2 5 C2
最后的记录不应该出现,因为它属于早期的选区。
答案 0 :(得分:1)
在我看来,你现在根本不应该按选区分组。下面的查询可以帮助您入门。
var query1 = from vote in db.Votes
group vote by vote.CandidateID into g
select new { CandidateID = g.Key, Count = g.Count() } into voteCount
join candidate in db.Candidates
on voteCount.CandidateID equals candidate.CandidateID
group voteCount by candidate.Constituency into constituencies
select constituencies.OrderByDescending(v => v.Count).First()
// Rest of query
第一个块首先计算每个候选人的投票数,然后按选区对这些候选/计数对进行分组,并仅选择第一个。那就是候选/计数对的序列,每个选区只有顶对。