gpt4 book ai didi

c#-4.0 - 如何让 FileHelpers 在每条记录上设置行号?

转载 作者:行者123 更新时间:2023-12-04 14:44:44 34 4
gpt4 key购买 nike

是否有机会让 MultiRecordEngine 为每条记录设置行号?
我阅读了文档,发现 Engine 有一个 LineNumber 属性,但我找不到使用它的方法。

我想要什么:
IE。:

[FixedLengthRecord]
public class Employee
{
public int LineNumber; // <-- setup by the engine while reading the file

[FieldFixedLength(1)]
public string Type = "2";

[FieldFixedLength(6)]
[FieldTrim(TrimMode.Left, "0")]
public int ID;
}

或者...我可以依赖 Engine.ReadFile 创建的集合中记录的索引吗?
IE。:
  static void Main(string[] args)
{

var engine = new MultiRecordEngine(CustomSelector, _types);
var obj = engine.ReadFile("order.txt");

// obj.GetValue(100) returns same record found on the 101th line in the file?
}

最佳答案

您可以使用 AfterReadRecord设置 LineNumber 属性的事件。

这是一个工作示例

public class Employee
{
[FieldIgnored]
public int LineNumber; // <-- setup by the engine while reading the file

[FieldFixedLength(1)]
public string Type = "2";

[FieldFixedLength(6)]
[FieldTrim(TrimMode.Left, "0")]
public int ID;
}

class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<Employee>();
engine.AfterReadRecord += engine_AfterReadRecord;
Employee[] records = engine.ReadString("2000003" + Environment.NewLine
+ "5000006");

Employee firstRecord = records[0];
Assert.AreEqual(1, firstRecord.LineNumber);
Assert.AreEqual("2", records[0].Type);
Assert.AreEqual(3, records[0].ID);

Employee secondRecord = records[1];
Assert.AreEqual(2, secondRecord.LineNumber);
Assert.AreEqual("5", records[1].Type);
Assert.AreEqual(6, records[1].ID);

Console.Read();
}

static void engine_AfterReadRecord(EngineBase engine, AfterReadEventArgs<Employee> e)
{
e.Record.LineNumber = engine.LineNumber;
}
}

关于c#-4.0 - 如何让 FileHelpers 在每条记录上设置行号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24491918/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com