Put parts of the fields in a dictionary
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.
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);
}
}
Yes, thanks.
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.
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
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);
}
}
}`
Sorry I am not sure what's wrong with the code formatting. I tried but couldn't make it work properly.
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:
{ CompanyName: Company1, Extra1: Extra1.1, Extra2: Extra2.1 }{ 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.
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?