【发布时间】:2016-11-23 18:02:24
【问题描述】:
如果我有一个看起来像下面的模型的类,那么有几个整数属性 Cand1Votes 、 Cand2Votes 和 Cand3Votes 需要在每个 Election 的视图中显示在 DescendingOrder 中目的。对于特定的选举,Cand1Votes 可能是第一个,Cand3Votes 第二个和Cand2Votes 第三个。
到目前为止,我的解决方案是为每个选举对象创建一个 List<KeyValuePair<string, int?>>,然后将其发送到 ViewModel 并在 View 中使用。
到目前为止,我的解决方案有效,但我正在寻找一种解决方案,通过该解决方案我可以动态地对对象中的整数元素进行排序,而无需创建另一个 List<KeyValuePair<string, int?>>。
我们将不胜感激。
型号
public class Elections{
public int Id { get; set; }
public int? TotalVotes { get; set; }
public int? Cand1Votes { get; set; }
public string Cand2Name { get; set; }
public int? Cand2Votes { get; set; }
public string Cand2Name { get; set; }
public string Cand3Name { get; set; }
public int? Cand3Votes { get; set; }
public int? OtherVotes { get; set; }
}
public static List<KeyValuePair<string, int?>> OrderByVotes(Election election)
{
var votesArray = new List<KeyValuePair<string, int?>>()
{
new KeyValuePair<string, int?>(election.Cand1Name, election.Cand1Votes),
new KeyValuePair<string, int?>(election.Cand2Name, election.Cand2Votes),
new KeyValuePair<string, int?>(election.Cand3Name, election.Cand3Votes),
new KeyValuePair<string, int?>("Other Candidates", election.OtherVotes)
};
var result = votesArray.OrderByDescending(k => k.Value);
return result.ToList();
}
【问题讨论】:
-
开车投反对票,关心一个原因?
-
我希望候选人在一个可观察的集合中,而不是将它们作为单独的变量。你可以将此集合设置为视图的集合源,并在视图中对其进行排序,如下所示:stackoverflow.com/questions/14992072/…
-
我敢打赌这个模型代表一个数据库表,但如果我错了,请纠正我。接受@AmittaiShapira 的建议会更容易,但如果这不是一个选项,那么在对象中重新排序到底是什么意思?您是否希望
Cand1Name和Cand1Votes包含最低投票名称/值,Cand2Name和Cand2Votes包含下一个最低值,等等? -
@Sam 我从来没想过。但这是我可以做到的另一种可能的方式。我最初的想法是按降序动态打印出候选人姓名和投票。
-
在这种情况下,如果你能像马特的回答中建议的那样重新考虑,你会让自己的生活更轻松。
标签: c# asp.net asp.net-mvc