如何在对象

时间:2016-11-23 18:02:25

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

如果我的类看起来像下面的模型,那么有几个整数属性Cand1VotesCand2VotesCand3Votes需要显示在DescendingOrder中在每个Election对象的视图中。对于特定的选举,Cand1Votes可能是第一个,而Cand3Votes秒和Cand2Votes第三个。

到目前为止,我的解决方案是为每个选举对象创建一个List<KeyValuePair<string, int?>>,然后将其发送到ViewModel并在视图中使用它。

我的解决方案到目前为止正常工作,但我正在寻找一种解决方案,我可以动态地对对象中的整数元素进行排序,而无需创建另一个List<KeyValuePair<string, int?>>。< / p>

任何帮助将不胜感激。

模型

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();
 }

1 个答案:

答案 0 :(得分:2)

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

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等候选人。