samedi 10 mars 2018

Casting PropertyDescriptor to List

I have following class:

public class Cmp
{
    public List<Tuple<string, string>> Hdd { get; set; }
    public string Cpu { get; set; }
    public string MonitorModel { get; set; }
    public List<Tuple<string, string>> OpticDriver { get; set; }
}

I am also using this code to convert List<Cmp> to CSV:

public static void WriteToCsv<T>(IEnumerable<T> data)
{
    var strBuilder = new StringBuilder();
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    foreach (PropertyDescriptor prop in props)
    {
        strBuilder.Append(prop.DisplayName); // header
        strBuilder.Append(",");
    }
    strBuilder.AppendLine();
    foreach (T item in data)
    {
        foreach (PropertyDescriptor prop in props)
        {
            strBuilder.Append(prop.Converter.ConvertToString(
                prop.GetValue(item)));
            strBuilder.Append(",");
        }
        strBuilder.AppendLine();
    }

    File.WriteAllText(@"C:\list.csv", strBuilder.ToString());
}

Just wondering How can I iterator over Hdd and OpticDriver properties inside WriteToCsv<T>. Currently the result is like this:

 Hdd            Cpu     MonitorModel    OpticDriver
(Collection)    CPU1    Monitor1        (Collection)
(Collection)    CPU2    Monitor2        (Collection)
(Collection)    CPU3    Monitor3        (Collection)

I want it to be like this:

 Hdd            Cpu     MonitorModel    OpticDriver
Hdd1-Hdd2       CPU1    Monitor1        Disk1-Disk2
Hdd1-Hdd2       CPU2    Monitor2        Disk1-Disk2
Hdd1-Hdd2       CPU3    Monitor3        Disk1-Disk2





Aucun commentaire:

Enregistrer un commentaire