使用LINQ遍历类属性 [英] Iterating over class properties using LINQ
问题描述
有一个ParsedTemplate类,它具有300多个属性(键入Details和BlockDetails). parsedTemplate对象将由函数填充.填充此对象后,我需要LINQ(或其他方式)来查找是否有任何属性,例如"body"或"img",其中IsExist=false
和Priority="high"
.
There is a ParsedTemplate class that it has over 300 property (typed Details and BlockDetails). The parsedTemplate object will be fill by a function. After filling this object I need a LINQ (or other way) to find is there any property like "body" or "img" where IsExist=false
and Priority="high"
.
public class Details
{
public bool IsExist { get; set; }
public string Priority { get; set; }
}
public class BlockDetails : Details
{
public string Block { get; set; }
}
public class ParsedTemplate
{
public BlockDetails body { get; set; }
public BlockDetails a { get; set; }
public Details img { get; set; }
...
}
推荐答案
您将需要编写自己的方法来使您的开胃菜.幸运的是,它不需要很长.像这样:
You're going to need to write your own method to make this appetizing. Fortunately, it doesn't need to be long. Something like:
static IEnumerable<Details> GetDetails(ParsedTemplate parsedTemplate)
{
return from p in typeof(ParsedTemplate).GetProperties()
where typeof(Details).IsAssignableFrom(p.PropertyType)
select (Details)p.GetValue(parsedTemplate, null);
}
然后,如果您想检查ParsedTemplate
对象上是否存在任何属性,则可以使用LINQ:
You could then, if you wanted to check if any property "exists" on a ParsedTemplate
object, for example, use LINQ:
var existingDetails = from d in GetDetails(parsedTemplate)
where d.IsExist
select d;
这篇关于使用LINQ遍历类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!