我的解决方案是编写自己的排序类并将其作为上下文添加到 nvelocity。我正在传递该字段以作为字符串排序并作为反射访问它。我还设置按字符串值升序或降序排序。我还传递了比较器的名称,并通过反射访问它。然后,我将 List 方法 OrderBy 或 OrderByDescending 与所选字段和比较器一起使用。
我确实在这里找到了部分代码:http: //zootfroot.blogspot.co.uk/2009/10/dynamic-linq-orderby.html
public class NvelocitySort
{
public List<MyObject> Sort(List<MyObject> list, string fieldAndMode, string comparerName)
{
fieldAndMode = fieldAndMode.Trim();
// Split the incoming string to get the field name and sort ascending or descending
string[] split = fieldAndMode.Split(' ');
// Set default sort mode
string mode = "asc";
// If sort mode not specified, this will be the field name
string field = fieldAndMode;
// If sort mode added split length shall be 2
if (split.Length == 2)
{
field = split[0];
if (split[1].ToLower() == "asc" || split[1].ToLower() == "ascending") mode = "asc";
if (split[1].ToLower() == "desc" || split[1].ToLower() == "descending") mode = "desc";
}
// If length is more than 2 or 0, return same list as passed in
else if (split.Length > 2 || split.Length == 0)
{
return list;
}
// Get comparer based on comparer name
IComparer<string> comparer = (IComparer<string>)Activator.CreateInstance(Type.GetType(string.Format("Namespace.{0}", comparerName)));
// Choose the sort order
if (mode == "asc")
return list.OrderBy(item => item.GetReflectedPropertyValue(field), comparer).ToList();
if (mode == "desc")
return list.OrderByDescending(item => item.GetReflectedPropertyValue(field), comparer).ToList();
// If sort order not asc/desc return same list as passed in
return list;
}
}
这是检索字段的反射方法。
public static string GetReflectedPropertyValue(this object subject, string field)
{
object reflectedValue = subject.GetType().GetProperty(field).GetValue(subject, null);
return reflectedValue != null ? reflectedValue.ToString() : "";
}
简单的比较器示例:
public class TextComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return string.Compare(x, y);
}
}
像这样添加到 Nvelocity 上下文中:
this.velocityContext.Put("sorter", new NvelocitySort());
从 Nvelocity 模板访问,如下所示:
#foreach($item in $sorter.Sort($listObject, "Name desc", "TextComparer"))
$item.Name
#end
希望它可以帮助别人...
编辑:找到了一种更好的方法(实现多个字段排序):
http: //www.codeproject.com/Articles/280952/Multiple-Column-Sorting-by-Field-Names-Using-Linq