. net iccomparable:如何实现

本文关键字:实现 何实现 iccomparable net | 更新日期: 2023-09-27 18:05:15

我有一个对象集合,我需要排序,但不确定如何。

有一个字符串属性,比如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;
    }

. net iccomparable:如何实现

如果你的优先级列表在编译时是已知的并且你可以使用它,那么你可以比较索引你正在排序的值:

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…

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

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

Using LINQ:

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

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

为要排序的对象创建一个新类:

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)
    }
}