排序列表< T>通过枚举,其中枚举出故障 [英] Sort a List<T> by enum where enum is out of order

查看:121
本文介绍了排序列表< T>通过枚举,其中枚举出故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a List of messages. Each message has a type.

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

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

The enum names are arbitrary and cannot be changed.

我需要返回排序的名单:嘘,酒吧,富,斗

I need to return the list sorted as: Boo, Bar, Foo, Doo

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

My current solution is to create a tempList, add the values in the order I want, return the new list.

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

推荐答案

使用<$ C另一种。$ C>的IComparer 将建立一个有序字典

An alternative to using IComparer would be to build an ordering dictionary.

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]);

这篇关于排序列表&LT; T&GT;通过枚举,其中枚举出故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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