Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over class properties using LINQ

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; }
    ...
}
like image 357
Ghooti Farangi Avatar asked Jun 14 '12 12:06

Ghooti Farangi


3 Answers

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();
like image 22
Botz3000 Avatar answered Oct 22 '22 16:10

Botz3000


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;
like image 141
Dan Tao Avatar answered Oct 22 '22 16:10

Dan Tao


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.

like image 33
Ilya Shpakovsky Avatar answered Oct 22 '22 16:10

Ilya Shpakovsky