c# - 在没有 Linq 的情况下使用字符串对 List<T> 进行排序

标签 c# list sorting datatable

有没有办法对 List<T> 进行排序?使用类似 "Name desc" 的字符串(与 DataTable.DefaultView.Sort 相同)而不是 Linq?

我正在尝试替换 DataTablesLists我需要它来执行此操作以与旧代码兼容。

解决方案

使用 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/

相关文章:

python - 在 Python 中有效地交换列表元素

python - 将列表的列表转换为元组列表的列表

c++ - C++ 中的合并排序实现问题

javascript - 如何对网页中具有多个不同参数的 JSON 进行排序?

java - 重复链表上的最后一个元素

swift - 如何在 Swift 中按属性对结构进行排序

c# - 后退按钮专注于列表操作

c# - 将 List<int> 拆分为连续数字组

c# - 如何运行迁移配置类的 Seed() 方法

c# - 如何在 C# 中将 IEnumerable 转换为自定义类型?