.NET IComparable:如何实现

时间:2011-08-12 09:38:00

标签: c# .net

我有一些我需要订购的物品,但不知道如何。

有一个名为Prop1的字符串属性,我想要排序。我想基于包含Prop1的所有可能值的字符串列表进行排序。

List<string> precedence = new List<string>() { "firstPrecedence", "secondPrecedence" ....

我如何实现CompareTo(object obj)方法?

我正在尝试这个,但不知道我在做什么!

    public int CompareTo(object obj)
    {
        List<string> precedence = new List<string>() { "firstPrecedence", "secondPrecedence", "thirdPrecedence" };

        Filter filterOther = obj as Filter;

        foreach (var item in precedence)
        {
            return String.Compare(filterOther.FilterValue, item);
        }
        return 0;
    }

4 个答案:

答案 0 :(得分:1)

好吧,如果您的优先级列表在编译时已知并且您可以使用它,那么您可以比较要排序的值的 索引

private static List<string> Precedence = new List<string>() { "item1", "item2", "item3" }; // etc

public int CompareTo(object obj)
{
    Filter item = obj as Filter; // Assume not null.   
    int otherIndex = Precedence.IndexOf(item.FilterValue);
    int thisIndex = Precedence.IndexOf(this.FilterValue); // Assume 'this' is a Filter

    // This may need to be otherIndex.CompareTo(thisIndex) depending on the direction of sort you want.
    return thisIndex.CompareTo(otherIndex);
}

如果FilterValue值不在列表中,IndexOf将返回-1,这仍将在此处的排序实现中起作用,但可以在列表的顶部或底部排序。我永远不记得哪个!

请注意,CompareTo方法返回0,小于0或大于0的内容。通常为-1,0和1。

此外,还有一个通用IComparable<>,它允许您以更强类型的方式实现此目的:

public class Filter : IComparable<Filter>
{

}

我相信一些聪明的人会在LINQ中给你一个解决方案......

答案 1 :(得分:1)

试试这个(假设你有一个List<Filter>

filterObjectList.Sort((f1,f2) => precedence.IndexOf(f1.FilterValue).CompareTo(precedence.IndexOf(f2.FilterValue));

答案 2 :(得分:0)

使用LINQ:

precedence.SelectMany(p => objs.Where(o => o.Prop1 == p));

OR

objs.Select(s => new { Index = precedence.IndexOf(s.Prop1), Obj = s })
                .OrderBy(a => a.Index).Select(a => a.Obj);

答案 3 :(得分:0)

创建要排序的对象的新类:

public class MySortableObject: IComparable {

    private string str;

    public MySortableObject(string _str) {
        this.str = _str;
    }

    int IComparable.CompareTo(object obj) {
        MySortableObject comparedObj = (MySortableObject) obj;

        // Implement here the code that will compare the current object (this) and the compared object (comparedObj)
        // It must return -1 if this instance precedes comparedObj in the sort order
        // It must return 1 if this instance follows comparedObj in the sort order
        // It must return 0 if this instance occurs in the same position in the sort order as comparedObj

        // Use for example String.CompareTo() method to implement this, or your own code (with if(), switch()... whatever you need)
    }
}