2011-11-18 74 views
3

我有IEnumerable集合。我想創建這樣的方法:如何過濾具有反射的任何屬性的集合?

public IEnumerable<object> Try_Filter(IEnumerable<object> collection, string property_name, string value) 
{ 
    //If object has property with name property_name, 
    // return collection.Where(c => c.Property_name == value) 
} 

這可能嗎?我正在使用C#4.0。 謝謝!

+0

就這麼很慢,使用4空間縮進,而不是8。代碼窗口不是那麼寬。 – Amy

回答

4

試試這個:

public IEnumerable<object> Try_Filter(IEnumerable<object> collection, 
string property_name, string value) 
    { 
     var objTypeDictionary = new Dictionary<Type, PropertyInfo>(); 
     var predicateFunc = new Func<Object, String, String, bool>((obj, propName, propValue) => { 
      var objType = obj.GetType(); 
      PropertyInfo property = null; 
      if(!objTypeDictionary.ContainsKey(objType)) 
      {   
       property = objType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(prop => prop.Name == propName); 
       objTypeDictionary[objType] = property; 
      } else { 
       property = objTypeDictionary[objType]; 
      } 
      if(property != null && property.GetValue(obj, null).ToString() == propValue) 
       return true; 

      return false; 
     }); 
     return collection.Where(obj => predicateFunc(obj, property_name, value)); 
    } 

測試了:

class a 
{ 
    public string t { get; set;} 
} 
var lst = new List<Object> { new a() { t = "Hello" }, new a() { t = "HeTherello" }, new a() { t = "Hello" } }; 
var result = Try_Filter(lst, "t", "Hello"); 
result.Dump(); 

雖然,這將是非常大的集合

+0

哇!非常感謝您的快速回答!它工作正常! – greatromul

+0

@greatromul不用擔心:)。此外,我忘了我現在添加的空檢查(如果您嘗試查找不存在的屬性,它會崩潰) – Rob

相關問題