試試這個:
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();
雖然,這將是非常大的集合
來源
2011-11-18 00:43:54
Rob
就這麼很慢,使用4空間縮進,而不是8。代碼窗口不是那麼寬。 – Amy