c# - 按枚举排序 List<T>,其中枚举乱序

标签 c# sorting

我有一个消息列表。 每条消息都有一个类型。

public enum MessageType
{
    Foo = 0,
    Bar = 1,
    Boo = 2,
    Doo = 3
}

枚举名称是任意的,不能更改。

我需要返回排序为:Boo、Bar、Foo、Doo 的列表

我目前的解决方案是创建一个 tempList,按我想要的顺序添加值,返回新列表。

List<Message> tempList = new List<Message>();
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Boo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Bar));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Foo));
tempList.AddRange(messageList.Where(m => m.MessageType == MessageType.Doo));
messageList = tempList;

我如何使用 IComparer 执行此操作? ?

最佳答案

使用 IComparer 的替代方法是构建一个排序字典。

var orderMap = new Dictionary<MessageType, int>() {
    { MessageType.Boo, 0 },
    { MessageType.Bar, 1 },
    { MessageType.Foo, 2 },
    { MessageType.Doo, 3 }
};

var orderedList = messageList.OrderBy(m => orderMap[m.MessageType]);

关于c# - 按枚举排序 List<T>,其中枚举乱序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17308818/

相关文章:

c# - C++ 中的垃圾回收

sql-server - 存储在 varchar 中的 SQL Server 混合数据类型中的自定义排序顺序

java - 来自比较器的未处理异常类型 ParseException

javascript - 按字母顺序对 Javascript 对象进行排序

c++ - std::stable_sort 根本不稳定?

javascript - 如何根据纬度和经度获取两个位置之间的距离?

c# - 为一个Form制作多个界面

C# 设置屏幕亮度 Windows 7

c# - SelectetValue 不返回 ASP.NET DropDownList 中的选定值

c# - 在 foreach 循环内的开关嵌套中使用 `continue` 关键字