urker
urker

Reputation: 123

How to pass anonymous property via lambda to a generic function?

I want to pass anonymous property using lambda to a generic function and access it there.
And how Do I access the property inside.

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

Upvotes: 0

Views: 917

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500923

You just call the delegate:

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))
   {

   }
}

Note that I had to change the type of the delegate to Func<TObject, int> as otherwise you couldn't compare it with iCurID.

Upvotes: 3

Related Questions