在linq中,我正在尝试使用动态排序列创建gridview 谁能帮我解决下面的代码以及为何不起作用
// i created this function to get column value which i need to sorty by
private static string GetReflectedPropertyValue( object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
// this is my grid query
List<ticketSearchRes> tickets = new List<ticketSearchRes>();
// here i deteermined sort direction ascending or desc
bool asc = (gridViewInputsVM.SortDirection == "asc") ? true : false;
bool desc = (gridViewInputsVM.SortDirection != "asc") ? true : false;
IQueryable<ticketSearchRes> source = (from ticket in _db.TblTicket
where (searchRes.assignTic == 1) ? ticket.AssignedTo == CurrentuserId : true
where (searchRes.myTicket == 1 && searchRes.forOthers != 1) ? ticket.CreatedFor == CurrentuserId : true
orderby
asc ? GetReflectedPropertyValue(ticket, "TicketTitle") : "",
// here i need to get dynamic column which i need to sort by
desc ? GetReflectedPropertyValue(ticket, "TicketTitle") : "" descending // doesn't work
select new ticketSearchRes
{
title = (ticket.TicketTitle != null) ? ticket.TicketTitle.ToString() : "",
ticId = ticket.TicketId.ToString()
}).AsQueryable();
答案 0 :(得分:0)
我该如何解决;
部分类TicketSearchResList
是填充部分方法CustomSort
的部分。 CustomSort接受属性名称和排序方向,并使用Reflection对命名的属性进行排序。到目前为止,应该很容易理解。
public partial class TicketSearchResList : List<TicketSearchRes>
{
partial void CustomSort(string propertyName, string direction);
public void Dump()
{
CustomSort("TicketTitle", "desc");
foreach(var ticket in this)
Console.WriteLine(ticket.ToString()); // For demo purposes
}
}
public partial class TicketSearchResList {
private string propertyName;
private string direction;
partial void CustomSort(string propertyName, string direction)
{
this.propertyName = propertyName;
this.direction = direction;
Sort(Comparer);
}
private int Comparer(TicketSearchRes x, TicketSearchRes y)
{
int directionChanger = direction == "asc" ? 1 : -1;
try
{
PropertyInfo lhs = x.GetType().GetProperty(propertyName);
PropertyInfo rhs = y.GetType().GetProperty(propertyName);
object o1 = lhs.GetValue(x, null);
object o2 = rhs.GetValue(y, null);
if(o1 is IComparable && o2 is IComparable)
{
return ((IComparable)o1).CompareTo(o2) * directionChanger;
}
// No sort
return 0;
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message); // Should log something
return 0;
}
}
使用Comparer方法中的Reflection完成比较。方向是
用于确定将结果乘以1还是-1。 CompareTo
返回
一个整数,其中-1表示小于,0表示等于,而1表示大于。因此,如果
将结果乘以-1,就可以改变排序的方向。
最后,TicketSearchResList
类继承自List<TicketResearchRes>
。如您所见,Dump方法调用CustomSort,如果实现,它会产生有序的输出。
另外,请查看由Microsoft here记录的Sort
方法