将哪个集合用于固定的值列表

本文关键字:列表 用于 集合 | 更新日期: 2023-09-27 18:07:51

我有如下数据,我想根据角度的方向填充在collection中。我希望集合的值是数量的总和。我应该使用哪个集合?

double angle = 20;
double quantity = 200;
double angle = 20;
double quantity = 250;
double angle = 30;
double quantity = 300;
double angle = 40;
double quantity = 400;

到目前为止,我已经尝试使用枚举创建dictionary,如下所示。我很确定这是不是一个好主意。有没有更好的办法

public enum Direction
{
    NorthToNortheast,
    NortheastToEast,
    EastToSoutheast,
    SoutheastToSouth,
    SouthToSouthwest,
    SouthwestToWest,
    WestToNorthwest,
    NorthwestToNorth
}

In my class

Dictionary<Direction, double> elements = new Dictionary<Direction, double>();

然后对于每个值,我将填充到字典

if (angle >= 0 && angle < 45)
    elements[Direction.NorthToNortheast] += quantity;
else if (angle >= 45 && angle < 90)
    elements[Direction.NortheastToEast] += quantity;

将哪个集合用于固定的值列表

您可以通过将方向和角度保存在列表中来简化方向查找,例如:

static readonly IReadOnlyList<CardinalDirection> _directionsByAngle = InitDirections();
// map each starting angle to a direction,
// sorted descending (largest angle first)
static IReadOnlyList<CardinalDirection> InitDirections()
{
    return new List<CardinalDirection>
    {
        new CardinalDirection (0, Direction.NorthToNortheast),
        new CardinalDirection (45, Direction.NortheastToEast),
        ...
    }
    .OrderByDescending(d => d.StartAngle)
    .ToList();
}
// find the first (largest) d.StartAngle such that angle >= d.StartAngle
static CardinalDirection GetDirectionForAngle(double angle)
{
    return _directionsByAngle
        .Where(d => angle >= d.StartAngle)
        .FirstOrDefault();
}

根据您想对值做什么,将总数保留在字典中,就像您现在使用的那样可以很好地工作。使用上面的代码片段,您将得到:

var direction = GetDirectionForAngle(angle % 360);
elements[direction.Direction] += quantity;

可以将每个枚举值用作收集器类中的属性:

//The class is describing your items
class Item
    {
        public double Angle;
        public double Quantity;
        public Item(double angle, double quantity)
        {
            Angle = angle;
            Quantity = quantity;
        }       
    }
//Collector class
class Element
{
    public Element()
    {
        NorthToNortheast.Quantity = 200;
        NorthToNortheast.Angle = 250;
        NortheastToEast.Quantity = 30;
        NortheastToEast.Angle = 300;
    }
    public Item NorthToNortheast { set; get; }
    public Item NortheastToEast { set; get; }
}