2

I'm currently working in ASP.NET with C# and ran into some problems.

I have the following class:

public class AvailableTicket
{
    public IEnumerable<Jazz> jazz;
    public IEnumerable<Dining> dining;
    public IEnumerable<Walking> walking;
    public IEnumerable<Talking> talking;

    public IEnumerable<Ticket> tickets;

    public int amountToOrder;
    public string Option;
}

In the view, I'd like to loop through the IEnumerables in the class. I've looked up GetType().GetProperties but I'm stuck here.

What do I use in the foreach to only select the IEnumerable in the object?

Thank you for your time.

Maarten G
  • 31
  • 3
  • Reflection is expensive, relative to other operations, you could either explicitly choose the elements you want to loop through, this is nice for programmers coming after you to see exactly what is happening but less useful if your object is still evolving and will have more collection elements, or you could put all the collections into a parent collection in order to avoid the reflection call. But good job on locating an answer for yourself. – user7396598 Apr 11 '18 at 23:52
  • Did you mean to define `jazz`,`dining`, etc. as properties? They are currently defined as public fields (considered a [bad practice](https://softwareengineering.stackexchange.com/questions/161303/is-it-bad-practice-to-use-public-fields)). – John Wu Apr 12 '18 at 00:33

2 Answers2

1

I found the solution myself.

I had to use

Model.GetType().GetProperties().OfType<IEnumerable<object>>()

in order to filter out all the IEnumerable within the class.

Maarten G
  • 31
  • 3
  • Are you sure that works? I think it will always return an empty set, since `GetProperties()` returns an array of type `PropertyInfo[]`. – John Wu Apr 11 '18 at 23:47
1

You need to filter the properties by their PropertyType and check to see if it is a type that implements an interface whose type definition is IEnumerable<>. Here's how to do it with LINQ:

Model.GetType().GetProperties().Where( p =>
    p.PropertyType.GetInterfaces().Any( i =>
        i.IsGenericType &&
        i.GetGenericTypeDefinition() == typeof(IEnumerable<>)
    )
);
John Wu
  • 50,556
  • 8
  • 44
  • 80