有没有办法对 List<T>
进行排序?使用类似 "Name desc"
的字符串(与 DataTable.DefaultView.Sort
相同)而不是 Linq?
我正在尝试替换 DataTables
与 Lists
我需要它来执行此操作以与旧代码兼容。
解决方案
使用 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() + "'");
}
}
}
最佳答案
List有一些排序方法,有些采用 Comparison<T>
您可以实现自定义比较和排序
关于c# - 在没有 Linq 的情况下使用字符串对 List<T> 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5815041/