Let's say, I have a Print method like this:
private static void Print(IEnumerable items)
{
// Print logic here
}
I want to pass a collection class to this Print method, which should print all the fields like a table. For example, my input collection can be "Persons" or "Orders" or "Cars" etc.
If I pass the "Cars" collection to the Print method, it should print the list of "Car" details such as: Make, Color, Price, Class etc.
I won't know the type of the collection until run-time. I tried and achieved a solution using TypeDescriptors
and PropertyDescriptorCollection
. But, I don't feel that is a good solution. Is there any other way to achieve this using expressions or generics?
You could implement Print like this:
static void Print<T>(IEnumerable<T> items)
{
var props = typeof(T).GetProperties();
foreach (var prop in props)
{
Console.Write("{0}\t", prop.Name);
}
Console.WriteLine();
foreach (var item in items)
{
foreach (var prop in props)
{
Console.Write("{0}\t", prop.GetValue(item, null));
}
Console.WriteLine();
}
}
It simply loops over each property of the class to print the name of the property, then prints over each item and for each item it prints the values of the properties.
I would argue that you should use generics here (as opposed to suggestions in other answers); you want the items in the collection to be of a single type so that you can print table headers.
For table formatting you can check the answers to this question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With