2012-05-02 72 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