2012-06-14 23 views
6

有一個ParsedTemplate類,它有300多個屬性(類型爲Details和BlockDetails)。 parsedTemplate對象將被函數填充。填充這個對象後,我需要一個LINQ(或其他方式)來查找是否有像「body」或「img」這樣的屬性,其中IsExist=falsePriority="high"使用LINQ對類屬性進行迭代

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; } 
    ... 
} 
+5

這是很容易用反射來做,但我不明白LINQ是如何有用的。爲什麼每個人都試圖用LINQ來解決所有問題? – cadrell0

+2

@ cadrell0因爲人們傾向於認爲LINQ是一顆銀子彈 – sloth

+2

@ cadrell0和所有那些激光的東西只是要LINQ – sloth

回答

7

你將需要編寫自己的方法來使這個開胃。幸運的是,它不需要很長時間。喜歡的東西:

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:

var existingDetails = from d in GetDetails(parsedTemplate) 
         where d.IsExist 
         select d; 
3

如果你真的想使用LINQ,而這樣做,你可以嘗試這樣的事情:

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

作品在我的機器上。

還是在擴展方法的語法:

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

使用C#反射。例如:

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

我還沒有編譯,但我認爲它的工作。

0
 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

雖然這與Dan Tao的回答相同,但它不如他的可重複使用(對於它試圖解決的問題,基本上太複雜了*如果您需要對任何變體重複此操作*)。 –