排序列表使用不带 Linq 的字符串

发布于 2024-11-03 15:39:32 字数 1937 浏览 0 评论 0原文

有没有办法使用像 "Name desc" 这样的字符串对 List 进行排序(与 DataTable.DefaultView.Sort 相同)然后林克?

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


    }
}

Is there a way to sort a List<T> using a string like "Name desc" (same as DataTable.DefaultView.Sort) rather then Linq?

I'm trying to replace DataTables with Lists and I need it to do this to be compatible with old code.

SOLUTION

using V4Vendetta's code I was able to create this extension method, tests seem to show it working.

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() + "'");
        }


    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

青丝拂面 2024-11-10 15:39:32

列表有一些排序方法,有些采用比较; 您可以实现自定义比较和排序

List has some sort methods and some take a Comparison<T> that you can implement to have custom comparison an sorting

多情出卖 2024-11-10 15:39:32

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

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

请参阅 codeplex 上的这篇文章作为示例: http://www.codeproject.com/KB /linq/dynamite_dynamic_sorting.aspx

There is no built-in support for this type of search as far as I know. So you will have to write your own.

It should not be too hard to parse the string. Split it on commas (,) in case you have a sort string like "name asc, age desc" and treat each as a name and a direction. Then you can use reflection on the type T to find the property to sort on and build a method that performs the needed comparison.

Look at this article on codeplex for an example: http://www.codeproject.com/KB/linq/dynamite_dynamic_sorting.aspx

睫毛上残留的泪 2024-11-10 15:39:32

我已经在这些方面尝试过一些东西,也许您需要根据您的需要即兴发挥它

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

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

希望这有帮助

I had tried something on these lines maybe you need to improvise it a cit for your need

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

You need to pass in the appropriate sort direction and the fieldname which would be property of the class (in my case Employee)

Hope this helps

调妓 2024-11-10 15:39:32

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

Look at the specialized collections name space. There should be a sorted list in there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文