简体   繁体   English

我如何写清单 <String> 放入.csv文件作为单列?

[英]How do I write a List<String> into a .csv file as a single column?

Right now I have a simple application where I have a C# object that has a List<String> as part of its attributes. 现在,我有一个简单的应用程序,其中有一个C#对象,该对象具有List<String>作为其属性的一部分。 It is supposed to store a list of strings alongside the other attributes and output it as a .csv file with headers. 应该将字符串列表与其他属性一起存储,并将其输出为带有标题的.csv文件。

After creating the object and outputting it as a .csv file, the column containing the list is not in the output and I don't know how to exactly handle it or converting it to a .csv format. 创建对象并将其输出为.csv文件后,包含列表的列不在输出中,而且我不知道如何精确处理该对象或将其转换为.csv格式。

My intended output is: 我的预期输出是:

Name,ID,Date,Number,FilePaths,Remarks
Value1, Value2, Value3, Value 4,List here,Value6

The output .csv file will then be serialized into JSON and be deserialized in another component where it is going to read the values and eventually be put into a database. 然后,输出的.csv文件将序列化为JSON,并在另一个组件中进行反序列化,该组件将读取值并将其最终放入数据库中。

The class (POCO): 班级(POCO):

class Object 
{
   public string Name { get; set; }
   public string ID { get; set; }
   public DateTime Date { get; set; }
   public long Number { get; set; }
   public List<String> FilePaths { get; set; }
   public string Messages {get; set; }
}

And here is how I instantiate the object from the data collected from inputs: 这是我从输入收集的数据中实例化对象的方法:

List<String> paths = new List<String>();

foreach(var file in files)
{
   paths.Add(file.FullName);
}

List<Object> newObject = new List<Object> {
new Object { Name = value1, ID = value2, Date = value3, Number = value4, FilePaths = paths, Messages = value6 };

using(var writer = new CsvWriter(outputStream))
{
   writer.WriteRecords(newObject);
}

However the output seems to be: 但是输出似乎是:

Name,ID,Date,Number,Remarks
value1,value2,value3,value4,value6

It seems to have skipped the list. 似乎已跳过列表。

EDIT: 编辑:

To elaborate further, the FilePaths are actually a list of strings that contain the directory paths of files the user has uploaded to the program. 为了进一步详细说明,FilePath实际上是一个字符串列表,其中包含用户已上传到程序的文件的目录路径。 What I plan to do is to have the list of file paths retrieved from List<FileInfo> files by calling a for loop and storing their paths into an organized fashion. 我计划要做的是通过调用for循环并将其路径存储为有组织的方式来从List<FileInfo> files检索文件路径的List<FileInfo> files This is because one user has the ability to upload multiple files as according to the requirements. 这是因为一个用户可以根据要求上载多个文件。

Declare FilePaths as string. 将FilePaths声明为字符串。 Convert List as the string you want and And then write to csv file. 将List转换为所需的字符串,然后将其写入csv文件。

Try initializing your list of object as the following: 尝试按以下方式初始化对象列表:

List<Object> newObject = new List<Object> {
            new Object {
                  Name = value1,
                  ID = value2,
                  Date = value3,
                  Number = value4,
                  FilePaths = paths.Any() ? $"\"{string.Join(",", paths.ToList())}\"" : null;,
                  Messages = value6
            }
      };

CsvHelper skips over Enumerable properties unless you give it more information on how it should handle them. CsvHelper会跳过Enumerable属性,除非您向其提供有关如何处理它们的更多信息。 This would be one way to output your CSV file by separating each FilePath value with a comma. 这是通过用逗号分隔每个FilePath值来输出CSV文件的一种方法。

public static void Main(string[] args)
{
    var paths = new List<string> { "path1", "path2", "path3" };

    List<Object> newObject = new List<Object> {
        new Object
        {
            Name = "NameValue",
            ID = "IdValue",
            Date = DateTime.Now,
            Number = 12345,
            FilePaths = paths,
            Messages = "MessagesValue"
        }
    };

    using (var csv = new CsvWriter(outputStream))
    {
        csv.Configuration.RegisterClassMap(new ObjectMap());
        csv.WriteRecords(newObject);
    }
}

public class ObjectMap : ClassMap<Object>
{
    public ObjectMap()
    {
        AutoMap();
        Map(m => m.FilePaths).TypeConverter<ListStringConverter>();
    }
}

private class ListStringConverter : StringConverter
{
    public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
    {
        var returnValue = string.Empty;

        var list = (List<string>)value;

        if (list != null)
        {
            returnValue = string.Join(",", list);
        }        

        return base.ConvertToString(returnValue, row, memberMapData);
    }

    public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
    {
        var list = text.Split(',').ToList();

        return list;
    }
}

public class Object
{
    public string Name { get; set; }
    public string ID { get; set; }
    public DateTime Date { get; set; }
    public long Number { get; set; }
    public List<String> FilePaths { get; set; }
    public string Messages { get; set; }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM