LINQ - 复杂的排序 [英] LINQ - Complex Sorting

查看:146
本文介绍了LINQ - 复杂的排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查询Order元素与LINQ(C#)的表。每个订单有以下字段:

I am querying a table of Order elements with LINQ (C#). Each Order has the following fields:

- ID
- OpenDate
- PriorityID
- StatusID
- Description



StatusID字段映射到一个状态表。状态表的结构为:

The StatusID field maps to a Status table. The Status table is structured as:

- ID
- Name

我需要得到所有其优先级和状态排序顺序对象。
我能顺利拿到按优先级排序的顺序对象。我通过
下面这样:

I need to get all of the Order objects sorted by their Priority and Status. I can successfully get the Order objects sorted by Priority. I'm doing this via the following:

List<Order> orders = new List<Order>();
using (DBDataContext context = new DBDataContext())
{
  orders = (from o in context.Orders
            orderby (o.PriorityID.HasValue ? o.PriorityID : Int32.MaxValue)  ascending
            select o).ToList();
}



但我的问题是在状态融通。

But my problem is factoring in the Status.

一旦订单对象已按优先级排序,我需要排序的Order对象
在状态的顺序如下:取消,打开,所有路线,并交付使用。显著,
这些状态值的ID以随机,非有帮助的顺序稳固。我不能改变他们。正如你所知道的,我也不能排序alphbetical名称的状态。另外,我不能添加任何字段我的数据库。谁能告诉我怎样才能在LINQ解决这个问题?

Once the order objects have been sorted by priority, I need to sort the Order objects in the following order of Status: Cancelled, Open, In-Route, and Delivered. Significantly, The IDs of these Status values are firmly set in a random, non-helpful order. I cannot alter them. As you can tell, I can't sort the status by alphbetical name either. In addition, I can't add any fields to my database. Can anyone tell me how I can solve this problem in LINQ?

感谢您!

推荐答案

我认为你必须解决这个通过实施的IComparer和使用LINQ订购。既然你的状态不是数字也不字母顺序

I think you have solution to this by implement IComparer and use Linq to order it. Since your Status is not in numeric nor alphabet order.

public class CustomComparer : IComparer<Status>
{
     public int Compare(Status statusA, Status statusB)
     {
       if (statusA.StatusName == "Cancelled" && statusB.StatusName == "Cancelled")
       {
          return 0; // equals
       } 
       else if (statusA.StatusName == "Cancelled" && statusB.StatusName != "Cancelled")
       {
          return 1; // A > B
       }
       ....
     }
}

然后

orders.OrderBy(x => x.Status, new CustomComparer())

希望这有助于。

这篇关于LINQ - 复杂的排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆