CsvHelper icon indicating copy to clipboard operation
CsvHelper copied to clipboard

Put parts of the fields in a dictionary

Open dvaosta opened this issue 6 years ago • 8 comments

Hi,

I hava a case in which my CSV contains a set of known fields plus an arbitrary number of other fields. I'd wish to map the known fields to the properties of a class in the usual way and put the others in a dictionary that is a property of that same class.

Is it possible with a ClassMap or something else to do this thing?

Thanks.

dvaosta avatar Jan 17 '20 07:01 dvaosta

Does this work for you? If you are not on version 13.0.0 remove CultureInfo.InvariantCulture from CsvReader

public class Program
{
    public static void Main(string[] args)
    {
        using (MemoryStream stream = new MemoryStream())
        using (StreamWriter writer = new StreamWriter(stream))
        using (StreamReader reader = new StreamReader(stream))
        using (CsvReader csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            writer.WriteLine("Id,Name,Column3,Column4,Column5");
            writer.WriteLine("1,One,Item1,Item2,Item3");
            writer.WriteLine("2,Two,Item4,Item5,Item6");
            writer.Flush();
            stream.Position = 0;
            reader.BaseStream.Position = 0;

            csv.Configuration.RegisterClassMap<FooMap>();

            var records = csv.GetRecords<Foo>().ToList();
        }
    }
}
    
public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Dictionary<string, string> OtherItems { get; set; }
}

public class FooMap : ClassMap<Foo>
{
    public FooMap()
    {
        Map(m => m.Id);
        Map(m => m.Name);
        Map(m => m.OtherItems).Index(2);
    }
}

AltruCoder avatar Jan 17 '20 18:01 AltruCoder

Yes, thanks.

dvaosta avatar Jan 20 '20 08:01 dvaosta

Hi. Is it possible to achieve the same but without relying on order/indices? I.e. map all the fields that are present in the model to the corresponding columns and all the values from all other columns should go to OtherItems.

magomedov avatar Apr 24 '20 15:04 magomedov

No. You would have to do this manually by looping the records. It should be fairly easy to do that though. https://joshclose.github.io/CsvHelper/examples/reading/reading-by-hand

JoshClose avatar Apr 24 '20 15:04 JoshClose

Hi Josh, Thanks for your reply. Actually I was playing with it and came up with a solution that works automatically: `[Test] public void TestDynamicMapping() { TextReader tr = new StreamReader(File.OpenRead("Data\testfile.csv")); var reader = new CsvReader(tr,CultureInfo.InvariantCulture); reader.Read(); reader.ReadHeader();

string[] headerRow = reader.Context.HeaderRecord;
reader.Configuration.RegisterClassMap(new CompanyMap(headerRow));

reader.Read();
var comp = reader.GetRecord<Company>();

reader.Dispose();

}`

and here is the test class and the mapping

`public class Company { public int PrimaryKey { get; set; } public int SourceId { get; set; } public string SourceName { get; set; } public string CompanyName { get; set; } public Dictionary<string, string> Extra { get; set; } }

public class CompanyMap : ClassMap<Company>
{
    public CompanyMap(string[] additionalHeaders)
    {
        Map(m => m.PrimaryKey);
        Map(m => m.SourceId);
        Map(m => m.SourceName);
        Map(m => m.CompanyName);

        foreach (var additionalHeader in additionalHeaders)
        {
            Map(m => m.Extra).Name(additionalHeader);
        }
    }
}`

magomedov avatar Apr 24 '20 16:04 magomedov

Sorry I am not sure what's wrong with the code formatting. I tried but couldn't make it work properly.

magomedov avatar Apr 24 '20 16:04 magomedov

It appears the solution provided by @magomedov still depends on the order. See e.g. the following example:

public static void Main(string[] args)
{
    using (var stream = new MemoryStream())
    using (var writer = new StreamWriter(stream))
    using (var reader = new StreamReader(stream))
    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        writer.WriteLine("Extra0,SourceId,PrimaryKey,SourceName,CompanyName,Extra1,Extra2");
        writer.WriteLine("Extra0.1,1,11,Item1,Company1,Extra1.1,Extra2.1");
        writer.WriteLine("Extra0.2,2,22,Item2,Company2,Extra1.2,Extra2.2");
        writer.Flush();
        stream.Position = 0;
        reader.BaseStream.Position = 0;

        csv.Read();
        csv.ReadHeader();
        var headerRow = csv.Context.HeaderRecord;

        csv.Configuration.RegisterClassMap(new CompanyMap(headerRow));

        var records = csv.GetRecords<Company>().ToList();
    }
}

The result for the Extra property will be:

  1. { CompanyName: Company1, Extra1: Extra1.1, Extra2: Extra2.1 }
  2. { CompanyName: Company2, Extra1: Extra1.2, Extra2: Extra2.2 }

All other properties have the expected value, but the Extra0 column is not included in the deserialized result, and CompanyName is added to the Extra dictionary.

SimonTouchtech avatar Jun 24 '20 09:06 SimonTouchtech

New syntax for CsvHelper Version="30.0.1"

public static void Main(string[] args)
{
      using (var stream = new MemoryStream())
      using (var writer = new StreamWriter(stream))
      using (var reader = new StreamReader(stream))
      using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
      {
          writer.WriteLine("Extra0,SourceId,PrimaryKey,SourceName,CompanyName,Extra1,Extra2");
          writer.WriteLine("Extra0.1,1,11,Item1,Company1,Extra1.1,Extra2.1");
          writer.WriteLine("Extra0.2,2,22,Item2,Company2,Extra1.2,Extra2.2");
          writer.Flush();
          stream.Position = 0;
          reader.BaseStream.Position = 0;

          csv.Read();
          csv.ReadHeader();
          var headerRow = csv.HeaderRecord;

          csv.Context.RegisterClassMap(new CompanyMap(headerRow));

          var records = csv.GetRecords<Company>().ToList();
      }
}
public class CompanyMap : ClassMap<Company>
{
    public CompanyMap(string[] additionalHeaders)
    {
        Map(m => m.PrimaryKey);
        Map(m => m.SourceId);
        Map(m => m.SourceName);
        Map(m => m.CompanyName);
        Map(m => m.Extra).Name(additionalHeaders);
    }
}
public class Company
{
  public int PrimaryKey { get; set; }
  public int SourceId { get; set; }
  public string SourceName { get; set; }
  public string CompanyName { get; set; }
  public Dictionary<string, string> Extra { get; set; }
}

The reading works flawlessly but there's a problem with recording:

var records = new List<Company> {
    new Company {
        SourceId = 1,
        PrimaryKey = 11,
        SourceName = "Item1",
        CompanyName = "Company1",
        Extra = new Dictionary<string, string>
        {
            { "Extra0", "Extra0.1"},
            { "Extra1", "Extra1.1"},
            { "Extra2", "Extra2.1"},
        }
    },
    new Company {
        SourceId = 2,
        PrimaryKey = 22,
        SourceName = "Item2",
        CompanyName = "Company2",

        Extra = new Dictionary<string, string>
        {
            { "Extra0", "Extra0.2"},
            { "Extra1", "Extra1.2"},
            { "Extra2", "Extra2.2"},
        }
    }
};

using (var writer = new StringWriter())
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.Context.RegisterClassMap(new CompanyMap(records[0].Extra.Select(x => x.Key).ToArray()));

    await csv.WriteRecordsAsync(records);
}

result:

PrimaryKey,SourceId,SourceName,CompanyName,Extra0
11,1,Item1,Company1,Extra0.1,Extra1.1,Extra2.1
22,2,Item2,Company2,Extra0.2,Extra1.2,Extra2.2

Header bad ((( I was expecting a headline like this:

PrimaryKey,SourceId,SourceName,CompanyName,Extra0,Extra1,Extra2

from docs:

/// <summary>
/// When reading, is used to get the field
/// at the index of the name if there was a
/// header specified. It will look for the
/// first name match in the order listed.
/// When writing, sets the name of the 
/// field in the header record.
/// The first name will be used.
/// </summary>
/// <param name="names">The possible names of the CSV field.</param>
public new virtual MemberMap<TClass, TMember> Name(params string[] names)
{
}

How can I write the full header including all dictionary keys?

mcka-dev avatar Nov 16 '22 06:11 mcka-dev