forrestDumb
forrestDumb

Reputation: 67

How to extract property names from custom class in C#

I am making function for exporting table to .csv file.

I have List where T is custom class.

I need property names of T for columns in .csv file.

How can I extract them to other List ?

Upvotes: 0

Views: 1069

Answers (3)

MarkPflug
MarkPflug

Reputation: 29518

I maintain some libraries that make this very easy: Sylvan.Data.Csv and Sylvan.Data.

The Sylvan.Data library provides an API for turning an IEnumerable<T> into a DbDataReader (AsDataReader). The Sylvan.Data.Csv library provides an API for writing DbDataReader to a CSV file (CsvDataWriter). You can combine these to make an extension method:

using Sylvan.Data;
using Sylvan.Data.Csv;

static class CsvMethods
{
    public static long WriteAsCsv<T>(this IEnumerable<T> seq, string file)
        where T : class
    {
        using var writer = File.CreateText(file);
        return WriteAsCsv(seq, writer);
    }

    public static long WriteAsCsv<T>(this IEnumerable<T> seq, TextWriter output) 
        where T : class
    {
        using var csvWriter = CsvDataWriter.Create(output);
        return csvWriter.Write(seq.AsDataReader());
    }
}

You can then write your List<T> to a CSV file with one line of code:

List<MyData> data = ...;
data.WriteAsCsv("mydata.csv");

The code implementing these libraries is extremely efficient, and will handle CSV edge-cases like fields containing delimiters, quotes, etc.

Upvotes: 1

Craig Craig
Craig Craig

Reputation: 13

Your question was a tad hard to understand. However I wrote some example code for you, hopefully it answers your question. As I believe you just needed help with the reflection part of the question.

using System.Reflection;

namespace Example
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            foreach (var type in types)
            {
                var props = GetProperties(type);

                foreach (var property in props)
                {
                    Console.WriteLine($"Type: {type.FullName} -> Property: {property.Name}");
                }
            }
        }

        public static PropertyInfo[] GetProperties(Type T)
        {
            return T.GetProperties();
        }
    }

    public class TestClass
    {
        public int Health { get; set; } // Example property
    }
}

Upvotes: 1

fbede
fbede

Reputation: 901

You can use reflection:

var propertyNames = typeof(T).GetProperties()
      .Select(p => p.Name));

Upvotes: 1

Related Questions