按特定顺序对字符串列表进行排序

时间:2013-12-04 09:58:15

标签: c#

这是我的班级:

class Example {
    string GridValue;
}

在我的代码中,我使用了一个我要排序的列表。 假设此列表具有以下值:

{
    "P", 
    "Q", 
    "X", 
    "H", 
    "J", 
    "L"
}

这是调用Sort()后我期望的输出:

{
    "X", 
    "Q", 
    "L", 
    "H", 
    "P", 
    "J"
}

如何使用IComparer接口实现此目的?

谢谢!

2 个答案:

答案 0 :(得分:4)

很简单,您编写了一个将您的特定订单考虑在内的Comparer:

public class ExampleComparer : IComparer<Example>
{
    private const string Order = "XQLHPJ";

    public int Compare(Example a, Example b)
    {
         int indexA = Order.IndexOf(a.GridValue);
         int indexB = Order.IndexOf(b.GridValue);
         if (indexA < indexB) { return -1; }
         else if (indexB < indexA) { return 1; }
         else { return 0; }
    }
} 

答案 1 :(得分:0)

如果每个字母都有一个已知的索引SortOrder(对于未知字母,我们可以设置默认索引):

class Example
{
    public string GridValue { get; set; }

    public int SortOrder { get; set; }
}

然后使用起来很简单:

var list = new List<Example>();
var result = list.OrderBy(itm => itm.SortOrder);

如果适用,请不要忘记语言问题,例如Turkey Test