2011-10-12 2 views
0

데이터베이스에서 가져온 개체 목록에서 일치하는 개체를 찾아서 개체를 새로 고침하고 싶습니다. 리플렉션으로 할 수는 있지만 Where 절 내에 Property Selector를 가져 오는 방법이 있어야합니다.람다 속성 선택기를 사용하는 Where 절

이 내가 호출 할 물건의 종류입니다 ...

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

하지만 방법에 붙어 조금 해요!

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! 

    } 
+0

당신은 선택과 같은 (X) 또는 somesuch, 객체에 선택기를 적용해야합니다. – bzlm

+1

"C# Lambda"와 같이 질문 앞에 접두사를 사용하지 마십시오. 그것이 바로 태그가있는 것입니다. –

답변

3

그냥 Lambdas와 IEnumerables로 작업하는 경우 정말 구문 분석이 필요합니까? 기본적으로 람다를 사용하십시오. 그게 당신의 호출 코드에 약간의 변화를 요구한다 :

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

방법 구현은 다음과 같습니다

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)); 
} 
+0

완벽한, 감사합니다. –