我有一个函数,我可以发送所有类型的项目的所有对象,它应该迭代属性并输出它们的值:
public void ShowMeAll(IEnumerable<object> items);
IEnumerable<Car> _cars = repository.GetAllCars();
ShowMeAll(_cars);
IEnumerable<House> _houses = repository.GetAllHouses();
ShowMeAll(_houses);
好的,例如,就是这样。现在,我想向我的ShowMeAll函数发送一个属性,我希望OrderBy我的项目然后输出。使用函数参数执行此操作的最正确方法是什么?
答案 0 :(得分:1)
最简单的方法是让LINQ通过the OrderBy() method为您做到这一点。例如:
IEnumerable<Car> _cars = repository.GetAllCars();
ShowMeAll(_cars.OrderBy(car => car.Make));
IEnumerable<House> _houses = repository.GetAllHouses();
ShowMeAll(_houses.OrderBy(house => house.SquareFootage));
这样,您就删除了ShowMeAll
要求了解传入的对象属性的要求。由于您正在传递List<object>
,我认为这是理想的。 :)
答案 1 :(得分:0)
private static void ShowMeAll<TClass>(IEnumerable<TClass> items, string property)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(TClass));
PropertyDescriptor targetProperty = properties.Find(property, true);
if (targetProperty == null)
{
// Your own error handling
}
IEnumerable<TClass> sortedItems = items.OrderBy( a => targetProperty.GetValue(a));
// Your own code to display your sortedItems
}
你可以这样调用这个方法:
ShowMeAll<Car>(_cars, "Make");
我遗漏了错误处理,因为我不知道你的要求是什么
答案 2 :(得分:0)
private static void ShowMeAll<TClass>(IEnumerable<TClass> items, string property )
{
// 1. Discover property type ONCE using reflection
// 2. Create a dynamic method to access the property in a strongly typed fashion
// 3. Cache the dynamic method for later use
// here, my dynamic method is called dynamicPropertyGetter
IEnumerable<TClass> sortedItems = items.OrderBy( o => dynamicPropertyGetter( o ) );
}
动态方法(比他们看起来容易,比我测试中的反射快50-100倍):http://msdn.microsoft.com/en-us/library/exczf7b9.aspx
表达式构建器也可以完成工作:http://msdn.microsoft.com/en-us/library/system.web.compilation.expressionbuilder.aspx
答案 3 :(得分:0)
有点这个?
public void Test()
{
var o = new[] {new {Name = "test", Age = 10}, new {Name = "test2", Age = 5}};
ShowMeAll(o, i => i.Age);
}
public void ShowMeAll<T>(IEnumerable<T> items, Func<T, object> keySelector)
{
items.OrderBy(keySelector)
.ToList()
.ForEach(t => Console.WriteLine(t));
}