[英]Create anonymous type by selector expressions
Is there a way to dynamically project a bunch of selector expressions into a new anonymous type that can be used for eg .Select() statements or combined member accessors? 有没有一种方法可以将一堆选择器表达式动态地投影到一个新的匿名类型中,该匿名类型可以用于例如.Select()语句或组合的成员访问器?
Let's say I've got a class with 3 properties 假设我有一个包含3个属性的课程
public class DummyClass {
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
}
In order to access one of them using a member accessor, I can write something like this: 为了使用成员访问器访问其中之一,我可以这样写:
public class DummyClass...
// x => x.Id
public static Expression<Func<DummyClass, int>> IdAccessor = f => Id;
Same goes for the Name
or Category
member. Name
或Category
成员也是如此。 Now I'd like to return both Id
and Name
as an anonymous type using both selectors. 现在,我想同时使用两个选择器将Id
和Name
作为匿名类型返回。
// combined x => x.Id and x => x.Name into x => new { x.Id, x.Name }
return new { IdAccessor, NameAccessor }
However I'm stuck doing this dynamically as I'm not able to create an anonymous type using eg Expression.New()
without knowing it's actual type. 但是,由于无法在不知道其实际类型的情况下使用Expression.New()
创建匿名类型,因此我一直动态地执行此操作。
EDIT 编辑
I rewrote the question with a different example that should clarify some more. 我用另一个例子重写了这个问题,应该进一步阐明。
Not sure what you really mean by "both selectors", but this is how I would make use of anonymous type; 不确定“两个选择器”的真正含义,但这就是我将使用匿名类型的方式。 when selecting specific values from a list of objects. 从对象列表中选择特定值时。 Please comment if this is not what you mean. 如果这不是您的意思,请发表评论。
var myDummies = new List<DummyClass> ...
var result = myDummes.Select(o => new
{
IdAccessor = o.Id,
NameAccessor = o.Name
Header = String.Format("{0} ({1})", o.Name, o.Category)
});
foreach(var r in result) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.