我想知道是否有一种方法可以根据类型从模型中选择元素。这是模型:
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);
基于此,验证签名(在决策模型内)是否为空。
欢迎任何帮助。
答案 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));
}
}
只需将object
替换为BaseModel
答案 1 :(得分:1)
要获取某个类型的所有属性,您需要使用反射。例如,您可以执行以下操作:
var decisions = typeof(Progress).GetProperties().Where(p => p.PropertyType == typeof(Decision)).ToArray();
之后,您可以遍历属性并执行您需要的任何操作。
如果需要检查对象(而不是类型本身),则需要调用以下内容如果Progress是用户对象的属性,则:
var decisions = user.Progress.GetType().GetProperties().Where(p => p.PropertyType == typeof(Decision)).ToArray();