我有以下数据,我希望根据角度的方向填充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
}
在我班上
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;
答案 0 :(得分:1)
您可以将每个枚举值用作收集器类中的Property:
//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; }
}
答案 1 :(得分:1)
您可以通过将方向和角度保持在列表中来简化方向查找,例如:
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;