2017-09-13 1 views
1

3 가지 상황에서 결과 집합이 95 % 동일한 상황이 있습니다. 5 % 차이는 주어진 변수에 따라 다르므로 나머지 5 %의 필드를 채 웁니다 (또는 포함하지 않음). 현재기존 IQueryable에 다중 선택을 추가하는 방법

public class MyResults { 
    public string PropertyA { get; set; } 
    public string PropertyB { get; set; } 
    public string PropertyC { get; set; } 
    public string PropertyD { get; set; } 
    public string PropertyE { get; set; } 
} 

나는 나는 다음과 같은 한 결과 구축하는 방법이 있습니다 :

public List<MyResults> GetMyResults(int someParameter) { 
    IQueryable<MyResults> query; 

    if (someParameter == "A") { 
    query = entities.Select(x => new MyResults { 
     PropertyA = x.PropertyA, // Common 
     PropertyB = x.PropertyB, // Common 
     PropertyC = x.PropertyC, // Different 
    }; 
    } else if (someParameter == "B") { 
    query = entities.Select(x => new MyResults { 
     PropertyA = x.PropertyA, // Common 
     PropertyB = x.PropertyB, // Common 
     PropertyD = x.PropertyD, // Different 
    }; 
    } else { 
    query = entities.Select(x => new MyResults { 
     PropertyA = x.PropertyA, // Common 
     PropertyB = x.PropertyB, // Common 
     PropertyE = x.PropertyE, // Different 
    }; 
    } 

    return query.ToList(); 
} 

을 간단한 예를 들어

, 여기에 돌려지고 결과 개체입니다 이것은 입니다. 원하는 작업 :

public List<MyResults> GetMyResults(int someParameter) { 
    IQueryable<MyResults> query = entities.Select(x => new MyResults { 
    PropertyA = x.PropertyA, // Common 
    PropertyB = x.PropertyB, // Common 
    PropertyC = x.PropertyC, // Common 
    }; 

    if (someParameter == "A") { 
    query = entities.Select(x => new MyResults { 
     PropertyC = x.PropertyC // Different 
    }); 
    } else if (someParameter == "B") { 
    query = entities.Select(x => new MyResults { 
     PropertyD = x.PropertyD // Different 
    }); 
    } else { 
    query = entities.Select(x => new MyResults { 
     PropertyE = x.PropertyE // Different 
    }); 
    } 

    return query.ToList(); 
} 

이 방법을 사용하면 모든 결과의 일관된 필드가 동일 해지고 다른 필드 만 추가하면됩니다.

이것이 가능합니까? 다음과 같이

+1

이상한 냄새가납니다. 왜 항상'PropertyC','PropertyD','PropertyE'를 설정할 수 없습니까? –

답변

3

당신은 삼항 연산자를 사용할 수 있습니다 null 될 것입니다 주어진 propertyX 속성 값의 경우 일치하지 않는 nullsomeParameter 경우

return entities.Select(x => new MyResults { 
    PropertyA = x.PropertyA, // Common 
    PropertyB = x.PropertyB, // Common 
    PropertyC = someParameter == 1 ? x.PropertyC : null, 
    PropertyD = someParameter == 2 ? x.PropertyD : null, 
    PropertyE = someParameter == 3 ? x.PropertyE : null, 
}).ToList(); 

은 기본적으로 string의 기본으로합니다. 그럴 경우 원하는 값을 얻습니다.

+0

글쎄, 뛰어난 지적. 이것은 효과가있다. 위에서 설계 한 것처럼 여러 개의 'Select'를 단일 쿼리로 병합하는 방법이 있습니까? – Grandizer

+1

@Grandizer - 좋은 방법은 아닙니다 ... 왜냐하면 당신이 실제로 낮은 수준을 선택하면 "업데이트"하지만 linq가 덜 적합하기 때문입니다. select는 새 객체를 투영하는 것입니다. 그렇게 할 수는 있지만 새 객체를 투영하고 모든 공통 속성을 다시 설정합니다. 어쩌면'Aggregate' 메쏘드를 사용할 수도 있지만 그 목적이 아닙니다. 나는 이것이 더 깨끗한 방법이라고 생각한다 –

+0

. 고마워요 @ 길다 드 – Grandizer

관련 문제