按我没有的属性重新排序列表

时间:2013-07-25 14:50:22

标签: c# list sorting

我在C#中有一个沼泽标准列表:List(其中Channel是一个电视频道)。频道定义为:

public class Channel
{
    public int ChannelId { get; set; }
    public string ChannelName { get; set; }
}

我的ORM填充了频道列表,这些频道来自频道ID顺序的数据库。我需要根据新的自定义排序属性重新排序列表,比如说ChannelOrder,但是我无法修改底层数据库。

有关如何执行此操作的任何想法,而不修改基础数据库?

例如,如果我当前来自db:

ChannelId = 1,ChannelName =“BBC1”,ChannelId = 2,ChannelName =“BBC2”,ChannelId = 3,ChannelName =“ITV”

我可能希望将它们命名为BBC2,BBC1,ITV,基本上是自定义订单。

2 个答案:

答案 0 :(得分:2)

如果您愿意在进程中(而不是作为查询的一部分)执行此操作,您可以使用:

var orderedChannelNames = new[] { "BBC2", "BBC1", "ITV", ... };
var sorted = unsorted.OrderBy(ch => orderedChannelNames.IndexOf(ch.ChannelName));

或者,如果您知道列表中的所有频道都会出现:

var map = unsorted.ToDictionary(ch => ch.ChannelName);
var sorted = orderedChannelNames.Select(name => map[name]);

答案 1 :(得分:0)

您可以使用另一个返回“附加”属性的类,类似于WPF中的附加属性:

public static class ChannelSort
{
    static Dictionary<Channel, int> _dict = new Dictionary<Channel, int>();
    public static int GetSort(this Channel c)
    {
        return _dict[c] //will throw if key's not found,
        //may want to handle it for more descriptive exception
    }
    public static int SetSort(this Channel c, int sort)
    {
        _dict[c] = sort;
    }
}

然后你可以这样做:

var result = unsortedList.OrderBy(c => c.GetSort());