2011-12-20 79 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)); 
}