如何确定表达式成员是否属于集合类型然后迭代该集合?

时间:2012-02-23 16:34:26

标签: c# lambda

示例类:

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;}
}

接受表达式集合的方法:

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.
   }

}

我可以这样称呼:

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

1 个答案:

答案 0 :(得分:1)

使用type关键字编译Expression后确定is

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

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