Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq - Order by StartsWith then Contains

Tags:

linq

Say i have 3 customer names:

Microsoft
Another customer also called Microsoft
A third customer called Microsoft

Now if i query the customers like this...

var q = (from cust in db.Cust
                    where cust.Name.Contains("Microsoft")
                    orderby cust.Name ascending
                    select cust)

...i get this order:

A third customer called Microsoft
Another customer also called Microsoft
Microsoft

What i want is to get Microsoft first, based on the fact that it starts with "Microsoft".

Changing Contains to StartsWith of course leaves me with 1 result instead of 3.

Could this be done in a single query?

like image 402
Malako Avatar asked Nov 04 '11 02:11

Malako


2 Answers

Maybe

var q = (from cust in db.Cust
                    where cust.Name.Contains("Microsoft")
                    orderby cust.Name.IndexOf("Microsoft"),
                             cust.Name.Length ascending
                    select cust)
like image 176
Valentin Kuzub Avatar answered Dec 14 '22 16:12

Valentin Kuzub


You could order by the percentage of the match.

orderby "Microsoft".Length * 1.0 / cust.Name.Length

This would yield 100% for just Microsoft and much less for the other matches.

like image 33
Austin Salonen Avatar answered Dec 14 '22 15:12

Austin Salonen