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

C# CSV转XML时如何筛选数组指定位置元素,跳过中间不需要字段

C# CSV转XML跳过中间指定字段的解决方案

你不需要依赖Skip方法实现跳过中间字段,直接预先定义需要保留的字段索引,只遍历这些索引读取对应列即可。
首先确认你提到的「第1、2、3、10、11、12位」是1起始的自然计数,对应代码中数组的0起始索引为0、1、2、9、10、11,如果你的索引规则不同,调整下方代码里保留索引数组的元素值即可。

修改后的完整代码如下:

var lines = File.ReadAllLines(path);
string[] headers = new string[13] {"PlantNo", "No", "Name", "cod_fatt", "tags_grp", "dos_type", "pervuoti", "cemq_chk", "rapp_ac", "code_01", "unit_01", "peso_01",""};
// 定义需要保留的字段索引(0起始)
int[] keepIndexes = new[] { 0, 1, 2, 9, 10, 11 };

var xml = new XElement("DC8_Recipes",
    // 跳过表头行
    lines.Skip(1).Select(line => 
    {
        var columns = line.Split(';');
        return new XElement("DC8_Recipes",
            // 仅遍历需要保留的索引,生成对应属性
            keepIndexes.Select(idx => new XAttribute(headers[idx], columns[idx]))
        );
    })
);

xml.Save(savepath);

优化说明

  • 原代码中对lunghezza循环赋值的逻辑完全冗余,已直接移除
  • 若担心CSV行存在缺列导致索引越界,可添加边界判断增强健壮性:
keepIndexes.Where(idx => idx < columns.Length).Select(idx => new XAttribute(headers[idx], columns[idx]))
  • 后续需要调整保留字段时,仅修改keepIndexes数组的元素即可,不需要改动其他逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 09:18:04