0

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

what is propertySelector? you mean property(x)?
@urker: Sorry, I meant to change the name of the parameter - personally I'd also change "iCurID" which is reasonably meaningless too.
@urker: It's not clear what you mean by "how do I access the property inside". What are you trying to do? Inside where?
@Jon Skeet, inside loop! get the property value: int x = cat.property;
@urker: You already know the value of the property - iCurID - otherwise it wouldn't have passed the Where clause to start with.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.