如何通过lambda将匿名属性传递给泛型函数?

时间:2011-04-02 11:23:52

标签: c# entity-framework generics lambda

我想使用lambda将匿名属性传递给泛型函数并在那里访问它 我如何进入内部的房产。

using (CommentsRepository commentsRepository = new CommentsRepository())
{
   var comments = commentsRepository.GetAllComments();

   Foo<Comment>(comments, 0,com=>com.ID); //Comment is an  EF entity
}

public static void Foo<TObject>(IEnumerable<TObject> list, int iCurID, <Func<TObject, TProperty> property) where TObject : class
{       
   foreach (var cat in list.Where(/*How to access the property*/==iCurID)
   {
          int x = cat.property;
   }
 }

1 个答案:

答案 0 :(得分:3)

您只需致电代表:

public static void Foo<TObject>
    (IEnumerable<TObject> list, 
     int iCurID,
     Func<TObject, int> propertySelector) where TObject : class
{       
   foreach (var cat in list.Where(x => propertySelector(x) == iCurID))
   {

   }
}

请注意,我必须将代理的类型更改为Func<TObject, int>,否则您无法将其与iCurID进行比较。