Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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) == null ? string.Empty : $"\"{f.GetValue(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) == null ? string.Empty : $"\"{f.GetValue(p)}\"")
            : list.Select(p => $"{f.GetValue(p)}")));
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading