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; }
...
}
If you really wanted to use linq while doing that, you could try something like that:
bool isMatching = (from prop in typeof(ParsedTemplate).GetProperties()
where typeof(Details).IsAssignableFrom(prop.PropertyType)
let val = (Details)prop.GetValue(parsedTemplate, null)
where val != null && !val.IsExist && val.Priority == "high"
select val).Any();
Works on my machine.
Or in extension method syntax:
isMatching = typeof(ParsedTemplate).GetProperties()
.Where(prop => typeof(Details).IsAssignableFrom(prop.PropertyType))
.Select(prop => (Details)prop.GetValue(parsedTemplate, null))
.Where(val => val != null && !val.IsExist && val.Priority == "high")
.Any();
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);
}
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;
Use c# reflection. For example:
ParsedTemplate obj;
PropertyInfo pi = obj.GetType().GetProperty("img");
Details value = (Details)(pi.GetValue(obj, null));
if(value.IsExist)
{
//Do something
}
I haven't compile but i think it work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With