To process data from a log file, I read the data into a list.
When I tried to convert from the list to an array for the graphing routine, I ran into trouble.
For the sake of this discussion, let's say the log file contains three values* - x, y and theta. In the routine that does file I/O, I read the three values, assign them to a struct and add the struct to PostureList.
The plotting routine, wants the x, y and theta to be in individual arrays. My thought was to use the ToArray() method to do the conversion but when I tried the syntax below, I got an error - see error in comment below. I have an alternate approach to do the conversion but wanted to get advice on better approaches.
I'm very new to C#. Thanks in advance for your help.
NOTE: * In reality, the log file contains many different pieces of information that have varying payload sizes.
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;
}
The ToArray
extension method can only be used on IEnumerable
s. To transform an IEnumerable
, for example from your struct to a single value, you can use the Select
extension method.
var xValues = PostureList.Select(item => item.x).ToArray();
var yValues = PostureList.Select(item => item.y).ToArray();
var thetaValues = PostureList.Select(item => item.theta).ToArray();
You don't need to define the size of the arrays or create them with new
, the extension method will take care of that.