2014-11-24 55 views
2

我有一个简单的物体,像这样的:使用LINQ通过Properties/reflection将单个对象转换为IEnumerable?

public class Foo { 
    public int One { get; set; } 
    public int Two { get; set; } 
    .... 
    public int Eleven { get; set; } 
} 

给出一个IEnumerable,我要的是一个LINQ的方法转化为这样:

myFooEnumerable.Select(n => transformMagicGoesHere); 

当我返回的对象是这样的:

public class Bar { 
    public string DurationDescription {get;set;} //Value would be "One" or "Two" or ... 
    public int Value {get;set;} //Holds value in the property One or Two or ... 
} 

因此,对于上例中myFooEnumerable中的每个项目N,我都会在结果选择语句中获得11(N)个项目。

回答

2

这应做到:

var bars = myFooEnumerable.SelectMany(
    x => x.GetType().GetProperties().Select(p => new Bar { 
     DurationDescription = p.Name, 
     Value = (int)p.GetValue(x) 
    })); 

不是一个伟大的事情摆在首位做,海事组织,但它至少会工作。

+0

谢谢。是的,我同意它并不理想,但这是对报告的转变,它不会影响性能敏感的代码或用作一般业务规则。 – Richthofen 2014-11-24 18:38:35

相关问题