我假设这里的“名称”和“测试结果”是灵活的,不能硬编码。
匿名类型是完全定义的常规类;关于它们的唯一有趣的事情是编译器提供了细节而不是你。
我建议处理这种情况的方法是使用Tuple.Create
创建一个IEnumerable<Tuple<string,string>>
并将它们称为Item1
, Item2
(来自的名称Tuple<,>
。另一种选择是使用类似的东西ExpandoObject
,然后使用IDictionary<string,object>
API 或dynamic
API 来取回值。
例如:
string item1 = "Name";
string item2 = "Test_Result";
Type studentType = typeof(Student);
var itemParam = Expression.Parameter(studentType, "x");
var member1 = Expression.PropertyOrField(itemParam, item1);
var member2 = Expression.PropertyOrField(itemParam, item2);
var selector = Expression.Call(typeof(Tuple), "Create",
new[] { member1.Type, member2.Type }, member1, member2);
var lambda = Expression.Lambda<Func<Student, Tuple<string,string>>>(
selector, itemParam);
var currentItemFields = students.Select(lambda.Compile());
name
这是具有成员和的自定义类型的相同投影result
:
class ProjectedData
{
public string name { get; set; }
public string result { get; set; }
}
...
string item1 = "Name";
string item2 = "Test_Result";
Type studentType = typeof(Student);
var itemParam = Expression.Parameter(studentType, "x");
var member1 = Expression.PropertyOrField(itemParam, item1);
var member2 = Expression.PropertyOrField(itemParam, item2);
var selector = Expression.MemberInit(Expression.New(typeof(ProjectedData)),
Expression.Bind(typeof(ProjectedData).GetMember("name").Single(), member1),
Expression.Bind(typeof(ProjectedData).GetMember("result").Single(), member2)
);
var lambda = Expression.Lambda<Func<Student, ProjectedData>>(
selector, itemParam);
var currentItemFields = students.Select(lambda.Compile());
或者对于使用字典的方法:
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);
var currentItemFields = students.Select(lambda.Compile());