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位置*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值