2014-11-24 35 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

相關問題