Is there a generic method to iterate and print a values in an unknown collection?

.net c# expression-trees generics lambda

Question

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?

Accepted Answer

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.


Popular Answer

Override the object's ToString() method to include all the information you would like to display, and then simply call it whenever you like. No need for expressions or generics.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why