Blingers
Blingers

Reputation: 883

C# Pivot a collection to create a csv with headers down the left side (vertically) and values on the right side (horizontal)

If I have a collection of models, e.g. a List where Header contains a set of properties. How can I display this such that the header titles are displayed on the left and the values are displayed as columns.

E.g.

So given I have 3 header records e.g.

public record Header 
{  
    public string BlNo;  
    public string Descr;  
    public int sigVal; 
}

var header = new Header { BlNo = "001", Descr = "test1", sigVal = 34 };
var header2 = new Header { BlNo = "002", Descr = null, sigVal = 38 };
var header3 = new Header { BlNo = "003", Descr = "test3", sigVal = 25 };
var headers = new List<Header>() {header, header2, header3};

How can I get the output to be:

,BlNo,"001","002","003"

,Descr,"test1",,"test3"

,sigVal,34,38,25

Upvotes: 1

Views: 39

Answers (1)

Konstantin Makarov
Konstantin Makarov

Reputation: 1376

static void PrintHeaderList<T>(List<T> list)
{
    var elmType = list.GetType().GetGenericArguments().Single();
    foreach (var f in elmType.GetFields())
    {
        Console.Write($",{f.Name},");
        Console.WriteLine(string.Join(",", f.FieldType == typeof(string)
            ? list.Select(p => f.GetValue(p)).Select(p => p == null ? string.Empty : $"\"{p}\"")
            : list.Select(p => f.GetValue(p))));
    }
}

or

static void PrintHeaderList<T>(List<T> list)
{
    var elmType = list.GetType().GetGenericArguments().Single();
    foreach (var f in elmType.GetProperties())
    {
        Console.Write($",{f.Name},");
        Console.WriteLine(string.Join(",", f.PropertyType == typeof(string)
            ? list.Select(p => f.GetValue(p)).Select(p => p == null ? string.Empty : $"\"{p}\"")
            : list.Select(p => f.GetValue(p))));
    }
}

Using:

PrintHeaderList(headers);

Upvotes: 1

Related Questions