使用不带Linq的字符串对List <T>进行排序

g.f*_*ley 6 c# sorting datatable list

有没有办法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() + "'");
        }


    }
}
Run Code Online (Sandbox Code Playgroud)

V4V*_*tta 2

我已经在这些方面尝试过一些东西,也许你需要即兴创作以满足你的需要

private List<Employee> CreateSortList<T>(
                    IEnumerable<Employee> dataSource,
                    string fieldName, SortDirection sortDirection)
    {
        List<Employee> returnList = new List<Employee>();
        returnList.AddRange(dataSource);
        // get property from field name passed
        System.Reflection.PropertyInfo propInfo = typeof(T).GetProperty(fieldName);
        Comparison<Employee> compare = delegate(Employee a, Employee b)
        {
            bool asc = sortDirection == SortDirection.Ascending;
            object valueA = asc ? propInfo.GetValue(a, null) : propInfo.GetValue(b, null);
            object valueB = asc ? propInfo.GetValue(b, null) : propInfo.GetValue(a, null);
            //comparing the items
            return valueA is IComparable ? ((IComparable)valueA).CompareTo(valueB) : 0;
        };
        returnList.Sort(compare);
        return returnList;
    }
Run Code Online (Sandbox Code Playgroud)

您需要传递适当的排序方向和字段名,这将是类的属性(在我的例子中是 Employee)

希望这可以帮助