【问题标题】:Sort List<T> using string without Linq使用没有 Linq 的字符串对 List<T> 进行排序
【发布时间】:2011-08-14 11:25:17
【问题描述】:

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

我正在尝试用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() + "'");
        }


    }
}

【问题讨论】:

    标签: c# list sorting datatable


    【解决方案1】:

    List 有一些排序方法,有些采用 Comparison&lt;T&gt;,您可以实现这些方法来进行自定义比较和排序

    【讨论】:

    • 我尝试了这个并一路学习。但是对上面的解决方案更满意,谢谢
    【解决方案2】:

    据我所知,此类搜索没有内置支持。所以你必须自己写。

    解析字符串应该不会太难。如果你有一个像“name asc, age desc”这样的排序字符串,则用逗号 (,) 将其拆分,并将每个字符串视为名称和方向。然后,您可以对类型 T 使用反射来查找要排序的属性并构建执行所需比较的方法。

    请看这篇关于 codeplex 的文章:http://www.codeproject.com/KB/linq/dynamite_dynamic_sorting.aspx

    【讨论】:

      【解决方案3】:

      我在这些方面尝试了一些东西,也许你需要即兴发挥它来满足你的需要

      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;
          }
      

      您需要传入适当的排序方向和作为类属性的字段名(在我的例子中是 Employee)

      希望对你有帮助

      【讨论】:

      • @g.foley 这对您有帮助吗?
      • 是的,这帮助最大。谢谢
      【解决方案4】:

      【讨论】:

      • 考虑到这个问题的标题中关于“没有 Linq”的部分很有趣。
      • 人们将 LINQ 与强类型扩展方法混为一谈并不罕见。动态查询库允许您使用字符串对列表进行排序,这可能会有所帮助。
      【解决方案5】:

      查看专门的集合名称空间。那里应该有一个排序列表。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-02
        • 1970-01-01
        相关资源
        最近更新 更多