Iterate class properties using LINQ

There is a ParsedTemplate class that has over 300 properties (typed data and BlockDetails). The parsedTemplate object will be populated with a function. After filling this object, I need LINQ (or another way) to find some 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; } ... } 
+6
source share
4 answers

You will need to write your own method to make this appetite. Fortunately, this does not have to be long. Sort of:

 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); } 

If you wanted to check if any property β€œexists” for the ParsedTemplate object, for example, use LINQ:

 var existingDetails = from d in GetDetails(parsedTemplate) where d.IsExist select d; 
+7
source

If you really want to use linq for this, you can try something like this:

 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(); 

It works on my car.

Or in the syntax of the extension method:

 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(); 
+3
source

Use C # reflection. For instance:

 ParsedTemplate obj; PropertyInfo pi = obj.GetType().GetProperty("img"); Details value = (Details)(pi.GetValue(obj, null)); if(value.IsExist) { //Do something } 

I am not compiling, but I think it works.

+1
source
  ParsedTemplate tpl = null; // tpl initialization typeof(ParsedTemplate).GetProperties() .Where(p => new [] { "name", "img" }.Contains(p.Name)) .Where(p => { Details d = (Details)p.GetValue(tpl, null) as Details; return d != null && !d.IsExist && d.Priority == "high" }); 
0
source

Source: https://habr.com/ru/post/918094/


All Articles