简体   繁体   English

LINQ 分组结果并按特定顺序排序

[英]LINQ grouping results and ordering them by specific order

I want to order my data like this:我想这样订购我的数据:

  1. Group my data by some value called "Type"按某个称为“类型”的值对我的数据进行分组

  2. I want to order groups by specific order of Types, for example: I have defined order: TYPE1, TYPE3, TYPE4,TYPE2我想按类型的特定顺序对组进行排序,例如:我定义了顺序:TYPE1、TYPE3、TYPE4、TYPE2

    And now I want all set to look like this:现在我希望所有设置看起来像这样:

    -first few rows are TYPE1 Type rows, - 前几行是 TYPE1 类型行,

    -next few rows are TYPE3 Type rows, -接下来的几行是TYPE3类型的行,

    ..... .....

Can anyone tell me how to achieve this?谁能告诉我如何实现这一目标?

You've mentioned that Type is an enum.您已经提到Type是一个枚举。 I can see two easy options for ordering this, 1. change the value of the enumeration members or, 2. use a custom ordering.我可以看到两个简单的排序选项,1. 更改枚举成员的值,或者 2. 使用自定义排序。

Solution 1 - Changing enumeration member values解决方案 1 - 更改枚举成员值

This is quite simple, but may not fit in with your requirements (ie the enumeration values may be dictated elsewhere or need hardcoded values).这很简单,但可能不符合您的要求(即枚举值可能在其他地方规定或需要硬编码值)。

Change the value of the enumeration members to be fixed values in the order you want:按照您想要的顺序将枚举成员的值更改为固定值:

public enumeration YourEnumName {
    TYPE1 = 1,
    TYPE3 = 2,
    TYPE4 = 3,
    TYPE2 = 4
}

Solution 2 - Use a custom list for ordering purposes解决方案 2 - 使用自定义列表进行排序

When conduction your ordering, create a list to dictate the order you want:在进行订购时,创建一个列表来指示您想要的顺序:

YourEnum[] orderList = new [] { YourEnum.TYPE1, YourEnum.TYPE3, YourEnum.TYPE4, YourEnum.TYPE2 };

var result = yourData.OrderBy(x => orderList.IndexOf(x.Type));

The limitation with this second solution is that if you have an item that does not exist in the orderList , then you will find that these are placed together in the order they were received at the start of the list.第二种解决方案的局限性在于,如果您有一个不存在于orderList中的项目,那么您会发现这些项目按照在列表开头收到的顺序放在一起。 There are solutions to that issue but I'm not clear on whether you will experience it.这个问题有解决方案,但我不清楚你是否会遇到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM