2017-05-16 20 views
0

我不知道是否有方法根據類型從模型中選擇元素。這裏是模型:c#根據類型從模型中選擇

public class Progress : BaseModel 
{ 
    public DateTime? LimitTime { get; set; } 
    public Status Status { get; set; } 
    public virtual Decision ApplicationDecision { get; set; } 
    public virtual Decision ValidationDecision{ get; set; } 
    public virtual Decision FinalDEcision { get; set; } 

    public virtual Outcome FinalChecksOutcome { get; set; } 
} 

public enum Status 
{ 
    Active, 
    Rejected 
    Completed 
} 

我想是這樣的:

var decisions = user.Progress.where(x=>x.type == Decision); 

所以此基礎上,以驗證是否簽名(決策模型中)爲空或不是。

任何幫助,歡迎。

+1

你嘗試與反思卻什麼? –

+0

沒有什麼反射,但 – George

回答

1

更換object爲了得到某種類型,你需要使用反射的所有屬性。例如,您可以執行以下操作:

var decisions = typeof(Progress).GetProperties().Where(p => p.PropertyType == typeof(Decision)).ToArray(); 

然後,您可以遍歷屬性並執行任何所需的操作。

如果您需要檢查的對象(而不是類型本身),你需要調用以下如果進展是用戶對象的屬性):

var decisions = user.Progress.GetType().GetProperties().Where(p => p.PropertyType == typeof(Decision)).ToArray(); 
+0

這工作相當不錯。謝謝。 – George

+0

不客氣! –

3

事情是這樣的:

class Program 
{ 
    static void Main(string[] args) 
    { 
     var t = new Container {Name = "Test", P1 = new MyType {Val = "1"}, P2 = new MyType {Val = "2"} }; 

     var res = t.OfType<MyType>(); 
    } 

    public class Container 
    { 
     public string Name { get; set; } 
     public MyType P1 { get; set; } 
     public MyType P2 { get; set; } 
    } 
    public class MyType 
    { 
     public string Val { get; set; } 
    } 
} 

public static class ObjectExtensions 
{ 
    public static Dictionary<string, T> OfType<T>(this object o) 
    { 
     return o.GetType().GetProperties().Where(p => p.PropertyType == typeof(T)).ToDictionary(p => p.Name, p => (T)p.GetValue(o)); 
    } 
} 

只是BaseModel