c# - 将列表中的结构体成员转换为数组

标签 c# list struct toarray

为了处理日志文件中的数据,我将数据读入列表中。

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

为了便于讨论,假设日志文件包含三个值* - 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;
}

最佳答案

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 创建数组,扩展方法会处理这些事情。

关于c# - 将列表中的结构体成员转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22754134/

相关文章:

c# - Asp.net 从代码后面添加表不能按预期工作

java - 如何使用 lambda/java8 迭代递归列表

java - Java中哪些List实现支持插入操作?

c++ - 如何从文本文件中输出数据? (学生成绩单计划)

c - 结构体内部固定大小数组的内存分配

c# - RabbitMQ 中的并发

c# - Expression<Action> 和 Expression<Action<T>> 之间的重载优先级

c# - 使用 new 隐藏非虚拟成员的替代方法

python - 将列表划分为偏移量为 1 的子列表

c - 使用 struct 的耗时 C 程序