知道linq有order by的功能,但是还是动手研究了一下,算是多实践实践反射。这篇算是笔记,直接上代码:

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)
                },
            };
            #endregion

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

//可以复用
            SortMutiplePropertyHelper<MySecondClass>.SortMutipleProperty(new List<MySecondClass>());

//输出排序结果
            list.ForEach(m => Trace.WriteLine(m.ToString()));
        }
    }

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

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

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

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

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

利用自定义特性实现List的多属性排序的更多相关文章

  1. 如何获取类或属性的自定义特性(Attribute)

    如何获取类或属性的自定义特性(Attribute) 问题说明: 在ActiveRecord或者其他的ORM等代码中, 我们经常可以看到自定义特性(Attribute)的存在(如下面的代码所示) [Pr ...

  2. C# winform利用反射和自定义特性加载功能模块(插件式开发)

    由于在实际的工作中, 碰见这样的一个问题: 一个软件, 销售给A客户 他需要所有功能, 但是销售给B客户, 他只需要其中的一部分, 1.如果我们在实际的开发过程中, 没有把一些功能模块区分开来的话, ...

  3. 利用自定义的AuthenticationFilter实现Basic认证

    [ASP.NET MVC] 利用自定义的AuthenticationFilter实现Basic认证   很多情况下目标Action方法都要求在一个安全上下文中被执行,这里所谓的安全上下文主要指的是当前 ...

  4. ____利用C#特性Attribute完成对sql语句的拼接

    //定义 特性类: public class MyAttribute : Attribute//自定义注解类判断是否是主键 { public bool PrimaryKey = false; publ ...

  5. 代码走查25条疑问 C# 跳转新的标签页 C#线程处理 .Net 特性 attribute 学习 ----自定义特性 看懂 ,学会 .NET 事件的正确姿势-简单版

    代码走查25条疑问   代码走查(Code Review) 是一个开发人员与架构师集中讨论代码的过程.通过代码走查可以提高代码的 质量,同时减少Bug出现的几率.但是在小公司中并没有代码走查的过程在这 ...

  6. Attribute自定义特性+Asp.net MVC中的filter详解

    转载自:http://blog.csdn.net/wangyy130/article/details/44241957 一.filter简介 在了解自定义特性前,先引入一个概念filter,它是MVC ...

  7. C#反射与特性(七):自定义特性以及应用

    目录 1,属性字段的赋值和读值 2,自定义特性和特性查找 2.1 特性规范和自定义特性 2.2 检索特性 3,设计一个数据验证工具 3.1 定义抽象验证特性类 3.2 实现多个自定义验证特性 3.3 ...

  8. JavaScript特性(attribute)、属性(property)和样式(style)

    最近在研读一本巨著<JavaScript忍者秘籍>,里面有一篇文章提到了这3个概念. 书中的源码可以在此下载.我将源码放到了线上,如果不想下载,可以直接访问在线网址,修改页面名就能访问到相 ...

  9. 【.net 深呼吸】自定义特性(Attribute)的实现与检索方法

    在.net的各个语言中,尤其是VB.NET和C#,都有特性这一东东,具体的概念,大家可以网上查,这里老周说一个非标准的概念——特性者,就是对象的附加数据.对象自然可以是类型.类型成员,以及程序集. 说 ...

随机推荐

  1. 视图view没有主键,但可以添加唯一索引

    视图没有主键,但可以加上唯一索引 大致可以这样理解:视图是张虚拟的表.视图所对应的数据不进行实际的存储,数据库中只存储视图的定义,对视图的数据进行操作时,系统根据视图的定义去操作与视图相关联的基本表. ...

  2. 5分钟构建无服务图片鉴黄web应用(基于FunctionGraph)

    函数工作流(FunctionGraph,FGS)是一项基于事件驱动的函数托管计算服务,托管函数具备以毫秒级弹性伸缩.免运维.高可靠的方式运行.即使在一些复杂的web应用场景中,函数工作流也能发挥出令人 ...

  3. cmake相关问题

    一.cmake升级 在ubuntu 16.04下面把cmake 由 3.5.1升级到 3.11,具体的流程如下所述. (1) sudo apt-get install build-essential ...

  4. 数据结构19: BF算法(普通模式匹配算法)

    判断两个串之间是否存在主串与子串的关系,这个过程称为串的模式匹配. 在串的模式匹配过程,子串 T 通常被叫做“模式串”. 普通的模式匹配(“BF”算法) 判断两个串是否存在子串与主串的关系,最直接的算 ...

  5. 2019-5-1 maven学习笔记

    一.maven的好处 同样的项目使用maven工程来实现,由于不需要导入很多jar包,源码很小 原理:根据坐标到项目的仓库里查找需要的依赖 二.安装步骤 1.到http://maven.apache. ...

  6. springboot整合mybatis,redis,代码(五)

    redis注解开发过程中包含许多注解 1.@Cacheable 可以标记在方法上,也可以标记在类上.当标记在方法上时表示该方法是支持缓存的,当标记在类上时则表示该类所有的方法都是支持缓存的.应用到读取 ...

  7. JDK的详细安装步骤

    jdk的安装 一.下载jdk安装包,可以从https://www.cnblogs.com/zyx110/p/10799387.html中查找并下载 二.双击打开jdk安装包,一路傻瓜式安装,点击下一步 ...

  8. Hanlp(汉语言处理包)配置、使用、官方文档

    配置使用教程:https://github.com/hankcs/HanLP Hanlp官方文档:http://www.hankcs.com/nlp/hanlp.html 参考API:http://h ...

  9. java 调用本地应用程序 Java打开(.word,.txt,.pdf)文件

    https://blog.csdn.net/lebron3v/article/details/80741000

  10. apache 日志分割

    Window apache 全局设置日志分割   apache  [ httpd.conf ] 配置文件 开启日志模块:LoadModule log_config_module modules/mod ...