Linq - 按StartsWith排序然后包含

时间:2011-11-04 02:54:01

标签: linq

假设我有3个客户名称:

Microsoft
Another customer also called Microsoft
A third customer called Microsoft

现在,如果我像这样查询客户......

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

...我收到此订单:

A third customer called Microsoft
Another customer also called Microsoft
Microsoft

我想要的是让微软第一,基于它以“微软”开头的事实。

将包含更改为StartsWith当然会留下1个结果而不是3个结果。

这可以在一个查询中完成吗?

2 个答案:

答案 0 :(得分:16)

也许

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

答案 1 :(得分:3)

您可以按比赛的百分比排序。

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

对于 Microsoft ,这将产生100%,而对于其他匹配则更少。