Reputation: 123
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
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