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

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

 

posted @ 2015-06-03 18:47  Ace001  阅读(2082)  评论(1编辑  收藏  举报