我在asp.net核心中有一个api(我是apis btw的新手),并且我试图通过类属性和该属性值过滤结果。如果我有一个名为类info
和它的属性attack
,defense
等等......该类型的属性是int
。用户希望看到的结果,其中attack > 5
或defense > 7
等..这里是我的类:
public class Champion
{
public string version { get; set; }
public string id { get; set; }
public string key { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
public string title { get; set; }
public string blurb { get; set; }
public info info { get; set; }
public string[] tags { get; set; }
//etc
}
public class Root
{
public Dictionary<string, Champion> data { get; set; }
}
public class info
{
public int attack { get; set; }
public int defense { get; set; }
public int magic { get; set; }
public int difficulty { get; set; }
}
public class stats
{
public double hp { get; set; }
public double hpperlevel { get; set; }
public double mp { get; set; }
public double mpperlevel { get; set; }
//etc
}
这是我的控制器:
[HttpGet("{property}/{value}")] //property is attack, defense, etc
public ActionResult Get(string property, int value)
{
var json = //json string;
var champions = JsonConvert.DeserializeObject<Root>(json);
info i = new info { };
//Here is what I am trying to implement
var returnValues = champions.data.Values
.Where(x => x.info.GetType()
.GetProperty(property)
.GetValue(i, null) > value);
//remaining code and return statement;
}
我想做的是returnValues
用作champions
对象中所有值的列表
Where(x => x.property > value).ToList()
。
当我使用GetType().GetProperty().GetValue() > value
我试图对象比较的int
.Where
要求bool
进行筛选。所以我的问题是如何实现这一目标?或者,还有更好的方法?
您应该将该对象转换为属性的实际类型。在这种情况下,它是一个int
。此外,您不需要其他null
参数。只是GetValue(yourObject)
会工作。您调用它并将其转换为您的媒体资源类型。
尝试这个:
var returnValues = champions.data.Values
.Where(x => (int) (x.info.GetType()
.GetProperty(property)
.GetValue(x.info)) > value);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句