DDiVita
DDiVita

Reputation: 4265

How to determine if an expression member is of a collection type and then iterate over that collection?

example classes:

public class Procedure: SomeBaseClass
{
     public Guid Id {get;set;}
     public ICollection<Task> Tasks {get;set;}

}

public class Task: SomeBaseClass
{
     public Guid Id {get;set;}
     public string Name {get;set;}
}

Method to take in expression colelction:

public viod DoSomethingWithProperties<T>(Guid enittyId, params Expression<Func<TEntity, object>>[] propertiesToDoStuffWith) where T: SomeBaseClass
{
   var item = someService<T>().FindById(entityId);
   .......

   foreach(var expression in propertiesToDoStuffWith)
   {
     ///I need to iterate the propertiesToDetach and determine if the property is a collection so I can perform operations on each item.
   }

}

I may call it like this:

DoSomethingWithProperties<Procedure>(1111-1111-1111-1111-1111,p => p.tasks);

Upvotes: 1

Views: 97

Answers (1)

Gabe
Gabe

Reputation: 50493

Determine the type after you compile your Expression by using the is keyword.

foreach(var expression in propertiesToDoStuffWith)
{
     var result = expression.Compile()(item);

     if (result is ICollection){
          // handle collection type
     }
     else {
          // some other type
     }
}

Upvotes: 1

Related Questions