利用自定義特性實現List的多屬性排序

知道linq有order by的功能,可是仍是動手研究了一下,算是多實踐實踐反射。這篇算是筆記,直接上代碼:ide

 

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;測試

namespace TestMultiplePropertySort
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 簡單測試數據
            var list = new List<MyClass>()
            {
                new MyClass()
                {
                    P1="h3",
                    P2=1,
                    P3=DateTime.Now
                },
                new MyClass()
                {
                    P1="h2",
                    P2=3,
                    P3=DateTime.Now.AddHours(-1)
                },
                new MyClass()
                {
                    P1="h1",
                    P2=2,
                    P3=DateTime.Now.AddHours(1)
                },
                new MyClass()
                {
                    P1="h3",
                    P2=1,
                    P3=DateTime.Now
                },
                new MyClass()
                {
                    P1="h1",
                    P2=1,
                    P3=DateTime.Now
                },
                new MyClass()
                {
                    P1="h2",
                    P2=2,
                    P3=DateTime.Now.AddHours(1)
                },
            };
            #endregionthis

            //調用多字段排序
            SortMutiplePropertyHelper<MyClass>.SortMutipleProperty(list);spa

            //能夠複用
            SortMutiplePropertyHelper<MySecondClass>.SortMutipleProperty(new List<MySecondClass>());排序

            //輸出排序結果
            list.ForEach(m => Trace.WriteLine(m.ToString()));
        }
    }ip

    public class MyClass
    {
        [SortOrder(0)]
        public string P1 { get; set; }字符串

        [SortOrder(1)]
        public int P2 { get; set; }get

        [SortOrder(2)]
        public DateTime P3 { get; set; }string

        public override string ToString()
        {
            return P1.ToString() + "," + P2.ToString() + "," + P3.ToString();
        }
    }it

    public class MySecondClass
    {
       
    }

    [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class SortOrderAttribute : Attribute
    {
        public int Order { get; set; }
        public SortOrderAttribute(int order)
        {
            this.Order = order;
        }
    }

    public class SortMutiplePropertyHelper<T> where T : class ,new()
    {
        /// <summary>
        /// 保存屬性和順序的字典
        /// </summary>
        public static readonly Dictionary<PropertyInfo, SortOrderAttribute> attrDic = new Dictionary<PropertyInfo, SortOrderAttribute>();

        static SortMutiplePropertyHelper()
        {
            //初始化order字段
            Type t = typeof(T);
            foreach (var prop in t.GetProperties())
            {
                foreach (var sortOrderAttribute in prop.GetCustomAttributes(typeof(SortOrderAttribute), false))
                {
                    if (sortOrderAttribute is SortOrderAttribute)
                    {
                        attrDic.Add(prop, sortOrderAttribute as SortOrderAttribute);
                        break;
                    }
                }
            }
        }

        public static void SortMutipleProperty(List<T> list)
        {
            list.Sort((t1, t2) =>
            {
                int result = 0;

                foreach (var attr in  attrDic.OrderBy(key => key.Value.Order))
                {
                    //這裏簡單的把屬性轉成字符串對比,比較靠譜的作法應當是針對不一樣的類型去作不一樣的比較。
                    string v1 = attr.Key.GetValue(t1).ToString();
                    string v2 = attr.Key.GetValue(t2).ToString();
                    result = v1.CompareTo(v2);
                    if (result != 0)
                    {
                        break;
                    }
                }

                return result;             });         }     } }

相關文章
相關標籤/搜索