英文:
How to get the field name to check if field should include quotes or not?
问题
我需要为某些字段添加引号。不应考虑字段类型,因为某些字符串应该有引号,而其他字符串不应该有引号。
所以我添加了以下配置:
var config = new CsvConfiguration(CultureInfo.InvariantCulture) {
ShouldQuote = args =>
{
var b = quoted.Contains(args.Field);
return b;
}
};
quoted
变量是需要引号的字段名称的列表。
但是 args.Field
不是字段名称,而是字段的值。在这个阶段是否有一种方法来检查字段名称是什么,或者也许有另一种方法来实现这一点?
英文:
I need to add quotes to some fields. The field type should not considered because some strings should have quotes and others not.
So I added the following configuration:
var config = new CsvConfiguration(CultureInfo.InvariantCulture) {
ShouldQuote = args =>
{
var b = quoted.Contains(args.Field);
return b;
}
};
The quoted
variable is a list of field names that need quotes.
But args.Field
is not the field name but the field value. Is there a way to check what the field name is at this stage or maybe there is another way to achieve this?
答案1
得分: 0
你可以使用 args.Row.HeaderRecord
以及 args.Row.Index
来确定字段的标题名称。如果你还想将实际的标题名称加上引号,你需要检查 args.field
,因为在那一点上 HeaderRecord
尚未填充。
void Main()
{
var quoted = new List<string> { "Id" };
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = args =>
{
if (args.Row.HeaderRecord != null)
{
return quoted.Contains(args.Row.HeaderRecord[args.Row.Index]);
}
if (args.Row.Row == 1)
{
return quoted.Contains(args.Field);
}
return false;
}
};
var records = new List<Foo>{
new Foo { Id = 1, Name = "Name1" },
new Foo { Id = 2, Name = "Name2" }
};
using (var csv = new CsvWriter(Console.Out, config))
{
csv.WriteRecords(records);
}
}
// Define other methods and classes here
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
英文:
You can use args.Row.HeaderRecord
along with args.Row.Index
to determine the header name of the field. If you also want the actual header name quoted, you will have to check args.field
since the HeaderRecord
will not have been populated at that point.
void Main()
{
var quoted = new List<string> { "Id" };
var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
ShouldQuote = args =>
{
if (args.Row.HeaderRecord != null)
{
return quoted.Contains(args.Row.HeaderRecord[args.Row.Index]);
}
if (args.Row.Row == 1)
{
return quoted.Contains(args.Field);
}
return false;
}
};
var records = new List<Foo>{
new Foo { Id = 1, Name = "Name1" },
new Foo { Id = 2, Name = "Name2" }
};
using (var csv = new CsvWriter(Console.Out, config))
{
csv.WriteRecords(records);
}
}
// Define other methods and classes here
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论