You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C# Apache Arrow库构建结构体列表的IArrowArray?

使用C# Apache Arrow库构建结构体列表的IArrowArray

修正原代码问题并完成完整实现

原代码中存在一处错误:new ListType(structField)里的structField未定义,应替换为提前声明的structType。以下是完整的可运行代码:

class Person
{
    public string name;
    public int age;
}

// 1. 构建Schema
Schema.Builder builder = new Schema.Builder();
var structType = new StructType(
    new[]
    {
        new Field("name", new StringType(), nullable: false),
        new Field("age", new Int32Type(), nullable: false)
    });
// 注意:ListType的参数是结构体类型structType
Field listField = new Field("listOfStructs", new ListType(structType), nullable: false);
builder.Field(listField);
Schema schema = builder.Build();

// 2. 准备业务数据
List<Person> people = new List<Person>();
people.Add(new Person { name = "Alice", age = 30 });
people.Add(new Person { name = "Bob", age = 25 });
people.Add(new Person { name = "Charlie", age = 40 });

// 3. 构建结构体的单个字段数组
// 构建name字段的StringArray
var nameArray = new StringArray.Builder().AddRange(people.Select(p => p.name)).Build();
// 构建age字段的Int32Array
var ageArray = new Int32Array.Builder().AddRange(people.Select(p => p.age)).Build();

// 4. 构建StructArray(包含3个Person实例对应的结构体元素)
var structArray = new StructArray(
    length: people.Count,
    fields: structType.Fields,
    children: new[] { nameArray, ageArray },
    nullCount: 0,
    nullBitmapBuffer: null // 所有元素非空,可传null
);

// 5. 构建ListArray(将StructArray作为列表的唯一元素)
// 偏移量缓冲区:[0, 3] 表示列表元素覆盖从索引0到3的结构体(左闭右开,实际包含3个元素)
var offsetsBuffer = new ArrowBuffer.Builder<int>().Append(0).Append(people.Count).Build();
var listArray = new ListArray(
    length: 1, // 列表本身只有1个元素(即整个people集合)
    offsetsBuffer: offsetsBuffer,
    values: structArray,
    nullCount: 0,
    nullBitmapBuffer: null
);

// 6. 创建RecordBatch,length对应ListArray的长度(1)
var recordBatch = new RecordBatch(schema, new[] { listArray }, length: 1);

关键缓冲区作用说明

  • offsetsBuffer(偏移量缓冲区):
    专为Arrow的ListType数组设计,存储列表中每个子元素的起始、结束偏移量,长度固定为列表长度 + 1。比如示例中ListArray只有1个元素,偏移量为[0,3],表示这个列表元素覆盖了索引0到3的结构体元素(实际包含3个元素)。如果是多元素列表,比如两个子列表,偏移量可能是[0,2,5],代表第一个子列表包含前2个元素,第二个包含后续3个。

  • nullBitmapBuffer(空值位图缓冲区):
    用二进制位标记数组中元素是否为null:1代表非空,0代表空值。如果数组所有元素都非空,可传入null或全1的位图;若存在空元素,则需要生成对应位图标记空值位置。

内容的提问来源于stack exchange,提问作者BAR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 07:22:46