GroupBy 표현식을 동적으로 생성하려면 Linq 표현식 트리를 작성하려고합니다. 그룹화 할 필드는 동적이며 번호가 다를 수 있습니다.GroupBy 표현식 트리를 여러 필드로 구성
은이 코드를 사용 : (! 감사합니다 마크 자갈)
string[] fields = {"Name", "Test_Result"};
Type studentType = typeof(Student);
var itemParam = Expression.Parameter(studentType, "x");
var addMethod = typeof(Dictionary<string, object>).GetMethod(
"Add", new[] { typeof(string), typeof(object) });
var selector = Expression.ListInit(
Expression.New(typeof(Dictionary<string,object>)),
fields.Select(field => Expression.ElementInit(addMethod,
Expression.Constant(field),
Expression.Convert(
Expression.PropertyOrField(itemParam, field),
typeof(object)
)
)));
var lambda = Expression.Lambda<Func<Student, Dictionary<string,object>>>(
selector, itemParam);
코드가 this post에서 복사합니다.
내가 람다 표현에 지나지 않는다 가정
var currentItemFields = students.GroupBy(lambda.Compile());
... 나는 그것에을 변경할 수 있다고 예상있는 ...
var currentItemFields = students.Select(lambda.Compile());
...로 확정 ...
var currentItemFields = students.GroupBy(o => new { o.Name, o.Test_Result });
...하지만 불행하게도 그럴 것 같지 않습니다. 동적 람다를 사용하는 GroupBy는 예외를주지 않으며, 단지 아무것도 그룹화하지 않고 모든 요소를 반환합니다.
내가 뭘 잘못하고 있니? 어떤 도움을 주시면 감사하겠습니다. 미리 감사드립니다.
, 무엇 모습 않습니다
는 다음과 같이 호출하려면? – Servy
@Servy 이렇게 : {x => new Dictionary'2() {Void Add (System.String, System.Object) ("Shift", Convert (x.Shift)), Void Add (System.String, System. Object) ("Section", Convert (x.Section))}} –
최종 결과가 사전이라는 사실을 알면 안되며 사전에 그룹화하면 그 내용이 아닌 사전의 참조. 결과가 분명해진다. – Servy