2012-05-02 79 views
3

可能重複的屬性:
LINQ: orderby with dynamic string parameter使用字符串作爲LINQ查詢

即時分選IEnumarable用的OrderBy()子句。我用一個包含我想要命令的字段的值的字符串列表。現在我使用每個屬性名稱的switch語句。

swich (propertyname) 
    case "name": 
     list = list.OrderBy(l=>l.name).ToList(); 
     break; 
    case "property": 
     list = list.OrderBy(l=>l.property).ToList(); 
     ..... 

是否有一個簡單的解決方案使用字符串「propertyname」作爲orderby子句中的屬性?

正如我所做的那樣,我得到的解決方案遠非理想。不僅更多的工作來編寫每個屬性,而且如果將來添加了任何屬性,這個更新將會在我正在寫的函數中被遺忘。

希望有人得到了更好的解決方案。

回答

2
var list = new List<MyClass>(); 

// Gets an object to give us access to the property with the given name of type MyClass 
var propertyInfo = typeof(MyClass).GetProperty(propertyName); 

// Each item is ordered by the value of the property 
list = list.OrderBy(x => propertyInfo.GetValue(x, null)).ToList(); 

解釋謂:

var xPropVal = propertyInfo.GetValue(x, null); 

使用屬性信息的對象,你得到的對象x的值,用空參數。 在這種情況下,參數將用於索引器,因爲這是屬性信息對象。

但由於這種情況下的屬性都是簡單的屬性,所以第二個參數應該是null或一個空的對象數組。

+0

但怎麼會如果propertyName將有更多的變種? – Likurg

+0

這不是問什麼。該字符串是該屬性的名稱,並且可能有多於2個。 – yamen

+0

該問題意味着有兩個以上的屬性。最後注意點。 – Stilgar