2014-03-31 109 views
1

要处理来自日志文件的数据,我将数据读入列表。将列表中的struct成员转换为数组

当我试图从列表转换为图表例程的数组时,我遇到了麻烦。

为了讨论起见,我们假设日志文件包含三个值* - x,y和theta。在执行文件I/O的例程中,我读取了三个值,将它们分配给一个结构并将结构添加到PostureList。

绘图程序,希望x,y和theta在单个数组中。我的想法是使用ToArray()方法进行转换,但是当我尝试下面的语法时,出现错误 - 请参阅下面的注释中的错误。我有一种替代方法来进行转换,但希望获得有关更好方法的建议。

我对C#很陌生。在此先感谢您的帮助。

注意:*实际上,日志文件包含许多不同的有效负载大小的不同信息。

struct PostureStruct 
{ 
    public double x; 
    public double y; 
    public double theta; 
}; 

List<PostureStruct> PostureList = new List<PostureStruct>(); 

private void PlotPostureList() 
{ 
    double[] xValue = new double[PostureList.Count()]; 
    double[] yValue = new double[PostureList.Count()]; 
    double[] thetaValue = new double[PostureList.Count()]; 

    // This syntax gives an error: 
    // Error 1 'System.Collections.Generic.List<TestNameSpace.Test.PostureStruct>' 
    // does not contain a definition for 'x' and no extension method 'x' accepting a first 
    // argument of type 'System.Collections.Generic.List<TestNameSpace.Test.PostureStruct>' 
    // could be found (are you missing a using directive or an assembly reference?) 
    xValue = PostureList.x.ToArray(); 
    yValue = PostureList.y.ToArray(); 
    thetaValue = PostureList.theta.ToArray(); 

    // I could replace the statements above with something like this but I was wondering if 
    // if there was a better way or if I had some basic mistake in the ToArray() syntax. 
    for (int i = 0; i < PostureList.Count(); i++) 
    { 
     xValue[i] = PostureList[i].x; 
     yValue[i] = PostureList[i].y; 
     thetaValue[i] = PostureList[i].theta; 
    } 

    return; 
} 

回答

2

ToArray扩展方法只能在IEnumerable上使用。要将转换为IEnumerable,例如从您的结构到单个值,可以使用Select扩展方法。

var xValues = PostureList.Select(item => item.x).ToArray(); 
var yValues = PostureList.Select(item => item.y).ToArray(); 
var thetaValues = PostureList.Select(item => item.theta).ToArray(); 

你不需要用new定义数组的大小或创建它们,扩展方法将采取照顾。

0

您试图直接在列表中引用x。

PostureList.y 

你需要做的是在特定成员像

PostureList[0].y 

我猜你需要从你的列表中选择所有的X。对于你能做到这一点

xValue = PostureList.Select(x => x.x).ToArray(); 
0

您可以用这种方式来您List<PostureStruct>转换为单个阵列:

double[] xValue = PostureList.Select(a => a.x).ToArray(); 
double[] yValue = PostureList.Select(a => a.y).ToArray(); 
double[] thetaValue = PostureList.Select(a => a.theta).ToArray(); 

这是你必须做的,该阵列才会有正确的尺寸(同作为名单的长度)。

0

您可以循环通过列表:

double[] xValue = new double[PostureList.Count()]; 
    double[] yValue = new double[PostureList.Count()]; 
    double[] thetaValue = new double[PostureList.Count()]; 

    foreach (int i = 0; i < PostureList.Count; ++i) { 
    xValue[i] = PostureList[i].x; 
    yValue[i] = PostureList[i].y; 
    thetaValue[i] = PostureList[i].theta; 
    } 

    ... 

或者使用的LINQ,但在不同方式:

double[] xValue = PostureList.Select(item => item.x).ToArray(); 
    double[] yValue = PostureList.Select(item => item.y).ToArray(); 
    double[] thetaValue = PostureList.Select(item => item.theta).ToArray(); 
    ...