创建前三名'具有相应百分比的整数列表

时间:2015-07-02 17:33:48

标签: c# asp.net linq

我正在创建一个人格测验,它会为用户提供多项选择答案,并在每次选择相应答案时添加这些答案:

public static int SubTally = 0;
public static int DomTally = 0;
public static int SimTally = 0;
public static int GroTally = 0;
public static int DefTally = 0;
public static int AccTally = 0;
public static int ConTally = 0;

在它添加到这些逻辑之后,我从这些中创建一个列表并选择max作为答案:

List<int> MyList = new List<int> 
{ 
   SubTallyResult, 
   DomTallyResult, 
   SimTallyResult, 
   GroTallyResult, 
   DefTallyResult, 
   AccTallyResult, 
   ConTallyResult 
};
int max = MyList.Max();

我现在想要取得前三名的最高记录并取每一个,除以总数,然后乘以100以获得它们的百分比。这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

您可以使用OrderByDescending按降序排序,然后使用Take 3个元素进行排序,并获取所需的输出,如:

var total = MyList.Sum();
var query = MyList.OrderByDescending(r=> r)
                  .Take(3)
                  .Select(r=> new 
                   {
                    Number = r, 
                    Percentage = ((double)r / total) * 100d,
                   });

答案 1 :(得分:1)

稍后您可能会遇到一些问题,即确定哪个统计数据位于前三位,这是另一种方法。

void Example()
{
    Random random = new Random();
    List<Tally> tallies = new List<Tally>
    {
        new Tally("SubTally", random.Next(0,100)),
        new Tally("DomTally", random.Next(0,100)),
        new Tally("SimTally", random.Next(0,100)),
        new Tally("GroTally", random.Next(0,100)),
        new Tally("DefTally", random.Next(0,100)),
        new Tally("AccTally", random.Next(0,100)),
        new Tally("ConTally", random.Next(0,100))
    };

    int sum = tallies.Sum(tally => tally.Score);
    var topThreeTallies = tallies.OrderByDescending(tally => tally.Score)
           .Take(3)
           .Select(tally => new 
           {
                tally.Name,
                tally.Score,
                Percentage =  ((decimal) tally.Score / sum) * 100M
            });

}

public class Tally
{
    public Tally(string name)
    {
        this.Name = name;
    }

    public Tally(string name, int score)
    {
        this.Name = name;
        this.Score = score;
    }

    public string Name { get; set; }
    public int Score { get; set; }
}

enter image description here