使用CSVHelper序列化和反序列化字典< TKey,Value>?

hivapdat  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(103)

是否可以使用字典中的CSVHelpers读取和写入CSV文件?
下面是我写的代码片段:

using var writer = new StreamWriter(_filePath);
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
if (_classMap != null)
{
    csv.Context.RegisterClassMap(_classMap);
}
csv.WriteHeader(typeof(Dictionary<TKey, TValue>));
csv.NextRecord();

foreach (var value in _store)
{
     csv.WriteRecord(new KeyValuePair<TKey,TValue>(value.Key,value.Value));
     csv.NextRecord();
}

字符串
下面是我读到的代码片段:

using var reader = new StreamReader(_filePath);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
_ = csv.Read();
_ = csv.ReadHeader();

if (_classMap != null)
{
    csv.Context.RegisterClassMap(_classMap);
}

while (csv.Read())
{
    var key = csv.GetField<TKey>(0);
    var value = csv.GetRecord<TValue>();

    _store[key] = value;
}


Dictionary的形状是<int,Sequence>类型,其中Sequence对象看起来像:

public class Sequence
{
    public int SequenceId { get; set; }
    public int NextId { get; set; }
}


我尝试了几种不同的方法来实现它,但每次都得到以下异常:

System.MissingMethodException: Constructor 'CsvHelper.Configuration.DefaultClassMap`1[[System.Collections.Generic.KeyValuePair`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e0
9],[FourDBS.SmartMeter.Common.Managers.Sequence, Four.DBS.Meadow.SmartMeter.Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]()'

uqcuzwp8

uqcuzwp81#

你很接近了你只需要写出字典id,然后写出Sequence值。阅读也是一样。使用GetField<int>("DictionaryId")GetRecord<Sequence>()。如果你想改变Sequence的编写方式,你可以使用ClassMap<Sequence>

void Main()
{
    var _filePath = @"C:\Temp\SerializeDictionary.csv";
    ClassMap<Sequence> _classMap = null;

    var data = new Dictionary<int, Sequence>(){
        { 1, new Sequence { SequenceId = 1, NextId = 2} },
        { 2, new Sequence { SequenceId = 2, NextId = 3} },
    };

    using (var writer = new StreamWriter(_filePath))
    using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
    {
        if (_classMap != null)
        {
            csv.Context.RegisterClassMap(_classMap);
        }
        csv.WriteField("DictionaryId");
        csv.WriteHeader<Sequence>();
        csv.NextRecord();

        foreach (var value in data)
        {
            csv.WriteRecord(value.Key);
            csv.WriteRecord(value.Value);
            csv.NextRecord();
        }
    }

    var _store = new Dictionary<int, Sequence>();
    using (var reader = new StreamReader(_filePath))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        _ = csv.Read();
        _ = csv.ReadHeader();

        if (_classMap != null)
        {
            csv.Context.RegisterClassMap(_classMap);
        }

        while (csv.Read())
        {
            var key = csv.GetField<int>("DictionaryId");
            var value = csv.GetRecord<Sequence>();

            _store[key] = value;
        }
    }
}

// You can define other methods, fields, classes and namespaces here
public class Sequence
{
    public int SequenceId { get; set; }
    public int NextId { get; set; }
}

字符串

m0rkklqb

m0rkklqb2#

为什么不为序列化/反序列化过程创建一个特定的类型呢?

public record DataRow(int Key, Sequence Value);

using var writer = new StreamWriter(_filePath);
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
if (_classMap != null)
{
    csv.Context.RegisterClassMap(_classMap);
}

csv.WriteRecords(_store.Select(pair => new DataRow(pair.Key, pair.Value));

字符串
阅读:

using var reader = new StreamReader(_filePath);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);

if (_classMap != null)
{
    csv.Context.RegisterClassMap(_classMap);
}

foreach(DataRow row in csv.GetRecords<DataRow>())
{
    if (row != null)
        _store[row.Key] = row.Value;
}

相关问题