有没有一种方法可以使用类似于“Name desc”(与DataTable.DefaultView.Sort相同)的字符串对List进行排序,而不是使用Linq?
我正在尝试用Lists替换DataTables,并且需要它能够执行此操作以与旧代码兼容。
解决方案:
使用V4Vendetta的代码,我能够创建这个扩展方法,测试似乎表明它可以工作。
我正在尝试用Lists替换DataTables,并且需要它能够执行此操作以与旧代码兼容。
解决方案:
使用V4Vendetta的代码,我能够创建这个扩展方法,测试似乎表明它可以工作。
public static void SortByString<T>(this List<T> list, string sortString)
{
if (sortString == null) return;
List<string> SortGroups = sortString.Split(',').ToList();
for (int i = SortGroups.Count - 1; i >= 0; i--)// sort from the last group first
{
string tempColumn = SortGroups[i].Trim().Split(' ')[0];
bool isAsc = SortGroups[i].Trim().Split(' ').Length > 1 ? SortGroups[i].Trim().Split(' ')[1].ToLower() == "asc" ? true : false : true;
PropertyInfo propInfo = typeof(T).GetProperty(tempColumn);
if (propInfo == null) // if null check to make sure its not just a casing issue.
{
foreach (PropertyInfo pi in typeof(T).GetProperties())
{
if(pi.Name.ToLower() == tempColumn.ToLower())
{
tempColumn = pi.Name;
propInfo = typeof(T).GetProperty(tempColumn);
break;
}
}
}
if (propInfo != null)
{
Comparison<T> compare = delegate(T a, T b)
{
object valueA = isAsc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);
object valueB = isAsc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);
return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;
};
list.Sort(compare);
}else{
throw new IndexOutOfRangeException("Property: '" + tempColumn + "', does not exist in '" + typeof(T).ToString() + "'");
}
}
}