对象中存在按属性名称对对象进行C#排序的数组 [英] C# Sort array of objects by property name exists in the object

查看:161
本文介绍了对象中存在按属性名称对对象进行C#排序的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码按对象中存在的任何属性名称(作为字符串)对对象的任何数组进行排序.

The following code, sorts any array of objects by any property name (as string) exists in the object.

排序数组也是使用排序方向"asc"或"desc"完成的.

Sorting array is done using sorting direction "asc" or "desc" too.

这是我要应用的目标.

    using System.Linq.Dynamic;

    /// <summary>
    /// This method sorts any array of objects.
    /// </summary>
    /// <param name="dataSource">Array of objects</param>
    /// <param name="propertyName">property name to sort with</param>
    /// <param name="sortDirection">"ASC" or "DESC"</param>
    /// <returns></returns>
    private object[] SortArrayOfObjects(object[] dataSource, string propertyName, string sortDirection)
    {
        string sortExpression = string.Format("{0} {1}", propertyName, sortDirection);
        // sortExpression will be something like "FirstName DESC".

        // OrderBy method takes expression as string like "FirstName DESC".
        // OrderBy method exists in "System.Linq.Dynamic" dll.
        // Download it from www.nuget.org/packages/System.Linq.Dynamic/
        object[] arrSortedObjects = dataSource.OrderBy(sortExpression).ToArray();

        return arrSortedObjects;
    }

推荐答案

您可以通过使方法成为通用方法以接受调用方法中的类型,然后使用类型参数T将dataSource强制转换为目标,来完成您想做的事情. /p>

You can do what you want by making the method generic to accept a type from the calling method, and then using type parameter T to cast the dataSource to.

private object[] SortArrayOfObjects<T>(object[] dataSource, string propertyName, string sortDirection)
    {
        string sortExpression = string.Format("{0} {1}", propertyName, sortDirection);
        // sortExpression will be something like "FirstName DESC".

        // OrderBy method takes expression as string like "FirstName DESC".
        // OrderBy method exists in "System.Linq.Dynamic" dll.
        // Download it from www.nuget.org/packages/System.Linq.Dynamic/
        object[] arrSortedObjects = dataSource.Cast<T>().OrderBy(sortExpression).Cast<object>().ToArray();

        return arrSortedObjects;
    }
}

// Use it like:       | You pass the type, so no need for hardcoding it, and it should work for all types.
SortArrayOfObjects<EmployeeInfo>(object[] dataSource, string propertyName, string sortDirection);

这是一个完整的演示:

将其放在DLL输出项目中: 使用系统; 使用System.Collections.Generic; 使用System.Text; 使用System.Collections.Generic; 使用System.Linq; 使用System.Linq.Dynamic;

Put this in a project of DLL output: using System; using System.Collections.Generic; using System.Text; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic;

namespace GenericMethod
{
    public class GenericMethodClass
    {
        public T[] SortArrayOfObjects<T>(object[] dataSource, string propertyName, string sortDirection)
        {
            string sortExpression = string.Format("{0} {1}", propertyName, sortDirection);
            // sortExpression will be something like "FirstName DESC".

            // OrderBy method takes expression as string like "FirstName DESC".
            // OrderBy method exists in "System.Linq.Dynamic" dll.
            // Download it from www.nuget.org/packages/System.Linq.Dynamic/
            T[] arrSortedObjects = dataSource.Cast<T>().OrderBy(sortExpression).ToArray();

            return arrSortedObjects;
        }
    }
}

将其放在控制台应用程序项目中,并确保引用包含上面代码的库: 使用系统; 使用System.Collections.Generic; 使用System.Text; 使用GenericMethod; 使用System.Linq;

Put this in a console app project and make sure to reference the library containing the code above: using System; using System.Collections.Generic; using System.Text; using GenericMethod; using System.Linq;

namespace GenericMethodApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            var employees = new object[]
            {
                new EmployeeInfo { FirstName = "Mohammed" },
                new EmployeeInfo { FirstName = "Ghasan" }
            };

            var students = new object[]
            {
                new Student { StudentName = "Mike" },
                new Student { StudentName = "Harris" }
            };

            var genericMethodClass = new GenericMethodClass();

            // Note that the generic method returns the array of the specific type
            // thanks to the T type parameter.
            EmployeeInfo[] returnedEmployees = genericMethodClass.SortArrayOfObjects<EmployeeInfo>(employees, "FirstName", "ASC");
            Student[] returnedStudents = genericMethodClass.SortArrayOfObjects<Student>(students, "StudentName", "ASC");

            foreach (var employee in returnedEmployees)
                Console.WriteLine(employee.FirstName);

            Console.WriteLine();

            foreach (var Student in returnedStudents)
                Console.WriteLine(Student.StudentName);

            Console.ReadKey();
        }
    }

    public class EmployeeInfo
    {
        public string FirstName { get; set; }
    }

    public class Student
    {
        public string StudentName { get; set; }
    }
}

您完成了.

确保在DLL中引用System.Linq.Dynamic.

Make sure to reference System.Linq.Dynamic inside the DLL.

这篇关于对象中存在按属性名称对对象进行C#排序的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆