zoukankan      html  css  js  c++  java
  • 【C#】 List按指定字段的给出的自定义顺序进行排序

    <div id="cnblogs_post_description" style="display: none">
        List按指定字段的给出的自定义顺序进行排序
    </div>
    

    正文

    #引言

    有一个集合,对其进行排序,排序规则为:按对象中某个字段的特定顺序进行排序,比如:对象属性id,按照【4,2,5,1】的顺序排序;

    #代码:

    1     public class Foo
    2     {
    3         public int Id { get; set; }
    4         public string Name { get; set; }
    5     }

    1、demo1:按字段id进行自定义排序

    复制代码
     1    List<Foo> foos = new List<Foo> {
     2        new Foo { Id = 1, Name = "b" }, new Foo { Id = 2, Name = "a" },
     3        new Foo { Id = 3, Name = "A" }, new Foo { Id = 4, Name = "B" }
     4    };
     5    int[] orderArr = new int[]{4,2,3,1};
     6    foos = foos.OrderBy(e =>
     7    {
     8        var index = 0;
     9        index = Array.IndexOf(orderArr, e.Id);
    10        if (index != -1) { return index; }
    11        else
    12        {
    13            return int.MaxValue;
    14        }
    15 
    16    }).ToList();
    17 
    18    foos.ForEach(p =>
    19    {
    20        Console.WriteLine(string.Format("Id:{0},Name:{1}",p.Id,p.Name));
    21    });
    复制代码

    ——————————————————————————————————————————————————————————————————


    作者:willingtolove

    出处:http://www.cnblogs.com/willingtolove/

    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

    <div id="blog_post_info">
    
    0
    0
    <div class="clear"></div>
    <div id="post_next_prev">
    
    <a href="https://www.cnblogs.com/willingtolove/p/10786860.html" class="p_n_p_prefix">« </a> 上一篇:    <a href="https://www.cnblogs.com/willingtolove/p/10786860.html" title="发布于 2019-04-28 21:32">【sql server】备份集中的数据库与现有数据库不同 解决方案</a>
    <br>
    <a href="https://www.cnblogs.com/willingtolove/p/10792713.html" class="p_n_p_prefix">» </a> 下一篇:    <a href="https://www.cnblogs.com/willingtolove/p/10792713.html" title="发布于 2019-04-29 21:19">【SQL】sql update 多表关联更新方法总结</a>
    
查看全文
  • 相关阅读:
    dedecms图片列表效果调用
    ThinkPHP 中M方法和D方法的具体区别
    在线更新dede程序后 网站出现错误 DedeCMS Error:Tag disabled:"php" more...!
    Form元素示例
    PHP使用frameset制作后台界面时,怎样实现通过操作左边框架,使右边框架中的页面跳转?
    删除UTF-8 BOM头的GUI小工具
    解决 ultraedit 菜单字体模糊
    git使用及一些配置、问题
    shell之基本语法
    shell之iptables
  • 原文地址:https://www.cnblogs.com/owenzh/p/13467745.html
  • Copyright © 2011-2022 走看看