gpt4 book ai didi

c# - CsvHealper - 如何忽略 csv 中的空列

转载 作者:行者123 更新时间:2023-12-05 03:59:05 24 4
gpt4 key购买 nike

csvHelper 的新功能。我想从 csv 文件中删除空列。我正在使用 CsvWriter 将 csv 行定义类写入流。

这是我的代码:

var records = getRecords(); // list of row definition items
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(records);
writer.Flush();
return stream;
}

有没有办法让 CsvWriter 忽略空列?也许配置?

actual csv: 

First Name | Middle Name| Last Name |Gender
FName1 | | LName1 | Male
FName2 | | LName2 | Female
FName3 | | LName3 |


expected csv:

First Name | Last Name |Gender
FName1 | LName1 | Male
FName2 | LName2 | Female
FName3 | LName3 |

最佳答案

可以使用配置来实现这一点。

public static void Main(string[] args)
{
var records = new List<Foo>
{
new Foo { FirstName = "FName1", LastName = "LName1", Gender = "Male"},
new Foo { FirstName = "FName2", LastName = "LName2", Gender = "Female"},
new Foo { FirstName = "FName3", LastName = "LName3"},
};

using (var csv = new CsvWriter(Console.Out))
{
var map = new FooMap();

var properties = typeof(Foo).GetProperties();

foreach (var property in properties)
{
if(records.All(foo => property.GetValue(foo) == null))
{
map.Map(typeof(Foo), property).Ignore();
}
}

csv.Configuration.RegisterClassMap(map);

csv.WriteRecords(records);
}

Console.ReadKey();
}

public class Foo
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
}

public class FooMap : ClassMap<Foo>
{
public FooMap()
{
Map(m => m.FirstName).Name("First Name");
Map(m => m.MiddleName).Name("Middle Name");
Map(m => m.LastName).Name("Last Name");
Map(m => m.Gender);
}
}

如果您不想创建单独的类映射,只需替换 FooMapDefaultClassMap<Foo>并使用 AutoMap .

var map = new DefaultClassMap<Foo>();
map.AutoMap();

关于c# - CsvHealper - 如何忽略 csv 中的空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57501382/

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