• linq order by charindex 排序 按给定字符串顺序排序


    //list=list.OrderBy(ee => SqlFunctions.CharIndex("书记,主任,支部委员,村委委员,系统工作人员", ee.ZhiWu)).ToList(); //linq to sql中报错:只能在linq to entities中调用此方法.
                int i = 0;

                list = list.OrderBy(ee => { i=Array.IndexOf(new string[] { "书记", "主任", "支部委员", "村委委员", "系统工作人员" }, ee.ZhiWu);if ( i!= -1) { return i; } else { return int.MaxValue; } }).ToList();  //字符串在字符数组中出现的位置,不在数组中的排在最后


    扩展: 如果字符串是 村委委员1  那么就不在字符串数组中了会排到后面去(如上图),下面函数解决模糊匹配问题

    int PatIndex(string[] array, string value)
            {
                int index = -1;
                for (int i = 0; i < array.Length; i++)
                {                
                    //if (value.Contains(array[i]))

    if (value.StartsWith(array[i]))//以搜索字符串开头的
                    {
                        index = i;
                        break;
                    }
                }
                return index;
            }

    list = list.OrderBy(ee => { i=PatIndex(new string[] { "书记", "主任", "支部委员", "村委委员", "系统工作人员" }, ee.ZhiWu);if ( i!= -1) { return i; } else { return int.MaxValue; } }).ToList();




    补充 sql:case when then

    select * from table order by case when cunorju like '%街道%' then 0 when cunorju like '%村委%' then 1 when cunorju like '%居委%' then 2 else 3 end

    sql order by charindex(...):

    Select * from table order by case when CharIndex(cunorju ,N'街道村委居委')>0 then CharIndex(cunorju ,N'街道村委居委')  else 2000000000 end

    /*符合的放最前面,不符合的排在2000000000位置*/

    版权声明:本文为博主原创文章,未经博主允许不得转载。

    作者:xuejianxiyang
    出处:http://xuejianxiyang.cnblogs.com
    关于作者:Heaven helps those who help themselves.
    本文版权归原作者和博客园共有,欢迎转载,但未经原作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

  • 相关阅读:
    LeetCode 面试题32
    LeetCode 102. 二叉树的层序遍历
    LeetCode 面试题32
    LeetCode 面试题32
    LeetCode 面试题31. 栈的压入、弹出序列
    LeetCode 946. 验证栈序列
    LeetCode 50. Pow(x, n)
    LeetCode 572. 另一个树的子树
    LeetCode 面试题50. 第一个只出现一次的字符
    LeetCode 面试题37. 序列化二叉树
  • 原文地址:https://www.cnblogs.com/xuejianxiyang/p/4862066.html
Copyright © 2020-2023  润新知