Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot control column order when exporting objects with nested objects #2172

Open
isak1080 opened this issue Aug 11, 2023 · 0 comments
Open
Labels

Comments

@isak1080
Copy link

When exporting a complex class containing nested objects, it is hard, and sometime impossible to control the ordering of columns (at least using attributes - let me know if there's another way to do this using class maps).

The main reason is because [Index] is treated as a global value.

Consider this example:

public class MainContent
{
    [Index(0)]
    public int Id { get; set; }
    [Index(1)]
    public int Name { get; set; }
    [Index(2)]
    [HeaderPrefix("First_")]
    public Range FirstRange { get; set; }
    [Index(3)]
    [HeaderPrefix("Second_")]
    public Range SecondRange { get; set; }
    [Index(4)]
    public string Comment { get; set; }
}

public class Range
{
    [Index(0)]
    public int From { get; set; }
    [Index(1)]
    public int To { get; set; }
}

// Using the types above
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (var csv = new CsvWriter(sw, CultureInfo.InvariantCulture))
{
    csv.WriteHeader(typeof(MainContent));
    csv.Flush();
}

Console.WriteLine(sb);

The column order I want to achieve is the following:
Id, Name, First_From, First_To, Second_From,Second_To,Comment

But what I get is this
Id,First_From,Second_From,Name,First_To,Second_To,Comment

I guess it's sort of expected, since we now have 3 columns with Index=0 (Id, First_From, Second_From) but it's

Describe the solution you'd like
I can think of three possible solutions

  1. Similar to [HeaderPrefix] - add a [IndexOffset] attribute that translates the local index of the nested object to unique value
  2. Treat [Index] as class local value.
  3. Add a new attribute [Order(n)], or [ExportIndex(n)] that is similar to [Index] that only controls ordering within the class during export.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant