Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

enumerate through all IEnumerables

Tags:

c#

ienumerable

I need to send different IEnumerables to an Printer object. This printer object will then do something to them, inside a foreach loop.

class Printer
{
    public Printer(IEnumerable list)
    {
        foreach (var enumerable in list)
        {
            //DO STUFF
        }
    }
}

This lets me send any enumerable, such as an List<T> to the printer object. such as

    var list = new List<string> {"myList"};
    new Printer(list); //mylist

This works fine. BUT if I send a Dictionary<T, T> such as:

var dictionary = new Dictionary<int, string> {{1, "mydict"}};
new Printer(dictionary); //[1, mydict]

It'll have a key and a value. What I would want though, would be separate access to the Value property inside the foreach loop. All I DO have access to is the enumerable object, which has no properties I can use.

Now what if the datatype T is an object containing several properties (this goes for both examples). How would I be able to use these properties in my foreach loop?

Do I honestly have to create an overload of the constructor, foreach possible datatype I might send down to it?

Also, all I need to do in the foreach is not dependable to any datatypes - as it won't manipulate everything. I do need ACCESS to all the properties though.

Also, this is just example code, not actually the production-code I use in my application.

like image 743
CasperT Avatar asked May 02 '26 03:05

CasperT


1 Answers

Can you change the code of the Printer class? If it accepted something like an IEnumerable<IPrintable> instead of just an IEnumerable it would be easier. With an interface like this:

interface IPrintable
{
    void Print();
}

Then all objects that would be sent to the Printer would need to implement that interface. Then you could do:

class Printer
{
    public Printer(IEnumerable<IPrintable> list)
    {
        foreach (var enumerable in list)
        {
            enumerable.Print();
        }
    }
}

And if you have a dictionary of printable objects, something like:

var dict = new Dictionary<int,IPrintable>();

You could just pass the values to the function:

var printer = new Printer(dict.Values);
like image 191
Meta-Knight Avatar answered May 03 '26 15:05

Meta-Knight