0

I want to be able to refresh an object by finding it's match in list of objects that I've got back from the database. I can do it with reflection - but am sure there must be a way of getting the Property Selector within a Where clause.

This is the kind of thing I want to call ...

MyObject = GetRefreshedObject(MyObject, RefreshedObjects, () => ID);

But I'm a bit stuck with the Method!

    public static TE GetRefreshed<TE, P>(TE entity, IEnumerable<TE> refreshed, Expression<Func<TE, P>> selector) where TE : class
    {
        if (entity == null) return null;

        return refreshed.Where(x => x.[Selector == entity.Selector]).FirstOfDefault();

        //The square bracket bits obviously don't work but hopefully show what I'm trying to achieve!

    }
2
  • You have to apply the selector to the object, like selector(x) or somesuch. Commented Oct 12, 2011 at 15:25
  • 1
    Please don't prefix your questions with things like "c# Lambda". That's what the tags are for. Commented Oct 12, 2011 at 15:27

1 Answer 1

3

If you are just working with Lambdas and IEnumerables, do you really need the expression parsing? Use the lambda natively. That would require a slight change to your calling code:

var refreshedObject = GetRefreshedObject(MyObject, RefreshedObjects, x => x.ID);

The method implementation would be:

public static TE GetRefreshed<TE, P>(TE entity, IEnumerable<TE> refreshed, Func<TE, P> selector)
{
  P myObjectId = selector(entity);
  return refreshed.FirstOrDefault(refresh => selector(refresh).Equals(myObjectId));
}
Sign up to request clarification or add additional context in comments.

Comments

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.