Linq - Order by StartsWith then Contains

Let's say I have 3 client names:

Microsoft Another customer also called Microsoft A third customer called Microsoft 

Now, if I request clients 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 request?

+6
source share
2 answers

Can

 var q = (from cust in db.Cust where cust.Name.Contains("Microsoft") orderby cust.Name.IndexOf("Microsoft"), cust.Name.Length ascending select cust) 
+14
source

You can order a percentage of the match.

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

This will give 100% only for Microsoft and much less for other matches.

+3
source

Source: https://habr.com/ru/post/900752/


All Articles