如何在Linq语句动态中使“s.Id”和“升序”?
var orderedList = from s in this.myList orderby s.Id ascending select s;
感谢
答案 0 :(得分:2)
var param = "Id";
var direction = "asc";
var propertyInfo = myList[0].GetType().GetProperty(param);
var orderById = myList.Select(x => new { item = x, sort = propertyInfo.GetValue(x) })
.OrderBy(x => direction == "asc" ? x.sort : 0)
.OrderByDescending(x => direction == "desc" ? x.sort : 0)
.Select(x => x.item)
.ToList();
答案 1 :(得分:0)
你可以这样做
var param = "Id";
var propertyInfo = typeof(yourObject).GetProperty(param);
var orderById = this.myList.OrderBy(x => propertyInfo.GetValue(x, null));