Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 352
Prince Ashitaka Avatar asked Feb 25 '11 05:02

Prince Ashitaka


Video Answer


1 Answers

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.

like image 139
Markus Johnsson Avatar answered Sep 29 '22 02:09

Markus Johnsson