【问题标题】:How to order properties within an object如何对对象中的属性进行排序
【发布时间】:2016-11-23 18:02:24
【问题描述】:

如果我有一个看起来像下面的模型的类,那么有几个整数属性 Cand1VotesCand2VotesCand3Votes 需要在每个 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 的建议更容易,但如果这不是一个选项,那么在对象中重新排序到底是什么意思?您是否希望 Cand1NameCand1Votes 包含最低投票名称/值,Cand2NameCand2Votes 包含下一个最低值,等等?
  • @Sam 我从来没想过。但这是我可以做到的另一种可能的方式。我最初的想法是按降序动态打印出候选人姓名和投票。
  • 在这种情况下,如果你能像马特的回答中建议的那样重新考虑,你会让自己的生活更轻松。

标签: c# asp.net asp.net-mvc


【解决方案1】:

我认为对模型进行一点重构会使这更容易一些:

public class Election
{
    public int Id { get; set; }
    public int TotalVotes { get; set; }
    public List<Candidate> Candidates { get; set; }

    public void AddCandidate(Candidate c)
    {
        Candidates.Add(c);
    }

    public List<Candidates> SortCandidates()
    {
        return Candidates.OrderByDescending(k => k.NumVotes).ToList();
    }
}

public class Candidate
{
     public string Name { get; set; }
     public int NumVotes { get; set; }        
}

这将允许任意数量的候选人在您的 Election 类中,并且您可以在 Election 对象上调用 SortCandidates() 方法以获取按 NumVotes 降序排序的候选人列表。遍历您视图上的候选人列表,以按顺序显示第 1、第 2、第 3 等候选人。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-26
    • 1970-01-01
    • 2015-06-20
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多