2011-12-20 52 views
2

我有一个函数,在那里我可以把所有类型的我的项目中的所有对象,它应该遍历性和输出他们的价值观:我怎么可能把我的类的属性,进入功能

public void ShowMeAll(IEnumerable<object> items); 

IEnumerable<Car> _cars = repository.GetAllCars(); 
ShowMeAll(_cars); 

IEnumerable<House> _houses = repository.GetAllHouses(); 
ShowMeAll(_houses); 

好例如,它是如此。现在,我想发送到我的ShowMeAll函数一个属性,我想订购我的项目,然后输出。用函数的参数做这件事最正确的方法是什么?

+0

@ FSoul1你的意思是在你想显示所有像ShowMeAll(_houses,SquareFootage)的属性或使用该命令在现有的财产通过发送? – msarchet 2011-12-20 01:13:52

+0

使用 – FSou1 2011-12-20 01:15:22

回答

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>,我认为期望的。 :)

+0

的顺序但我想变化一个属性,我可以使OrderBy和实现它的功能。 – FSou1 2011-12-20 01:16:20

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

我省略了错误处理,因为我不知道你的要求是

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

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