表示3个值的最佳方式 [英] Best way to represent sets of 3 values
问题描述
我有一个PHP背景。在PHP中,我会用像这样的3D关联数组来完成它:
position [time] [x] [ y]
所以我可以在某个时间访问x,y值。你会如何在C#中做到这一点?我认为像名单和字典这样的泛型会这样做。但我不知道如何为3D数据集实现键值。 解决方案
它看起来像要访问在给定时间的x / y位置。您可能会考虑其他答案和字典的组合。
定义一个简单的结构体,其中包含x& y位置。
public struct位置
{
public int X {get ; }
public int Y {get; }
public Position(int x,int y)
{
this.X = x;
this.Y = y;
$ b现在你可以将它们存储在字典中(可能) DateTime
作为键。 字典<日期时间,位置> positions = new Dictionary< DateTime,Position>();
positions.Add(新的DateTime(2017,3,29,10,0,0),新的Position(10,10));
您可以像
var pos = positions [new DateTime(2017,3,29,10,0,0)];
Console.WriteLine({0}:{1},pos.X,pos.Y);
除此之外,例如,您将得到一个您希望查找的对象列表,然后您可以轻松地将它们转换为字典。说你得到这些列表(从其他答案):
public class PositionEntity
{
public DateTime Time {get; set;}
public int X {get; set;}
public int Y {get; set;}
}
作为列表 entities
,您可以这样做:
IEnumerable< PositionEntity>实体= ....从某处加载
var dict = entities.ToDictionary(k => k.Time,v => new Position(v.X,v.Y));
Assume that I have 100 sets of 3 values. first value is time, second value is x position and 3rd value is y position. this is going to be the xy position of a point over 100 seconds for example.
I have a PHP background. in PHP I would do it with a 3D associative array like this :
position["time"]["x"]["y"]
so I can access x,y values at a certain time. How would you do this in c#? I think generics like list and dictionary would do that. but I don't know how to implement key values for a 3D set of data.
解决方案 It looks like you want to access an x/y position at a given time. You might consider a combination of the other answers along with a dictionary.
Define a simple struct which holds x & y positions. It is important that this object is immutable.
public struct Position
{
public int X { get; }
public int Y { get; }
public Position(int x, int y)
{
this.X = x;
this.Y = y;
}
}
Now you can store these in a dictionary with (perhaps) DateTime
as the key.
Dictionary<DateTime, Position> positions = new Dictionary<DateTime, Position>();
positions.Add(new DateTime(2017,3,29,10,0,0), new Position(10,10));
And you can read your position like
var pos = positions[new DateTime(2017,3,29,10,0,0)];
Console.WriteLine("{0}:{1}",pos.X,pos.Y);
A neat little addition to this is that if, for example, you are getting a list of these object you wish to lookup by time you can easily turn them into a dictionary. Say your get a list of these (from other answer):
public class PositionEntity
{
public DateTime Time {get;set;}
public int X {get;set;}
public int Y {get;set;}
}
As a list entities
you can do this:
IEnumerable<PositionEntity> entities = .... loaded from somewhere
var dict = entities.ToDictionary(k => k.Time, v => new Position(v.X,v.Y));
这篇关于表示3个值的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!