列表对齐,最简单的实现方式
本文关键字:实现 方式 最简单 对齐 列表 | 更新日期: 2023-09-27 18:00:39
我有以下列表:
100->1.0
99->1.1
98->1.1
97->1.2
23-28->5.6
0-5->6.0
左边是最大到达点,右边是坡度。此列表包含大约40个不同的分数->等级。所以我的程序是计算考试的分数,最后应该说达到了100分,你得到了1.0…3分达到了->6.0…
根据我目前的知识,我只知道切换的情况,但我认为这不是实现它的最佳方式。
我将从您所拥有的列表的数据结构开始。(顺便说一句,这是假设C#为6,对于早期版本的C#,您将无法使用自动实现的只读属性,但这是唯一的区别。)
public sealed class GradeBand
{
public int MinScore { get; }
public int MaxScore { get; } // Note: inclusive!
public decimal Grade { get; }
public GradeBand(int minScore, int maxScore, decimal grade)
{
// TODO: Validation
MinScore = minScore;
MaxScore = maxScore;
Grade = grade;
}
}
你可以用构建你的列表
var gradeBands = new List<GradeBand>
{
new GradeBand(0, 5, 6.0m),
...
new GradeBand(23, 28, 5.6m),
...
new GradeBand(100, 100, 1.0m),
};
你可能想要某种验证,证明这些级别涵盖了所有级别。
然后有两个相当明显的选项来查找等级。首先,无需预处理的线性扫描:
public decimal FindGrade(IEnumerable<GradeBand> bands, int score)
{
foreach (var band in bands)
{
if (band.MinScore <= score && score <= band.MaxScore)
{
return band.Grade;
}
}
throw new ArgumentException("Score wasn't in any band");
}
或者你可以对波段进行一次预处理:
var scoreToGrade = new decimal[101]; // Or whatever the max score is
foreach (var band in bands)
{
for (int i = band.MinScore; i <= band.MaxScore; i++)
{
scoreToGrade[i] = band.Grade;
}
}
然后对于每个分数,您可以使用:
decimal grade = scoreToGrade[score];
尝试此示例
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Dictionary<int, double> dictionary =
new Dictionary<int, double>();
dictionary.Add(100, 1.0);
dictionary.Add(99, 1.1);
//Add more item here
// See whether Dictionary contains a value.
if (dictionary.ContainsKey(100))
{
double value = dictionary[100];
Console.WriteLine(String.Format("{0:0.0}",value));
}
Console.ReadLine();
}
}