开发者

Can we sort an IList partially?

IList<A_Desc,A_pre开发者_JAVA技巧mium,B_Desc,B_Premium>

Can I sort two columns A_Desc,A_premium...based on A_Desc ?

And let B_Desc,B_Premium be remain in same order before sorting


First off, a list can only be of one type, and only has one "column" of data, so you actually want two lists and a data type that holds "desc" and "premium". "desc" sounds like a String to me; I don't know what Premium is, but I'll pretend it's a double for lack of better ideas. I don't know what this data is supposed to represent, so to me, it's just some thingie.

public class Thingie{
    public String desc;
    public double premium;
}

That is, of course, a terrible way to define the class- I should instead have desc and premium be private, and Desc and Premium as public Properties with Get and Set methods. But this is the fastest way for me to get the point across.

It's more canonical to make Thingie implement IComparable, and compare itself to other Thingie objects. But I'm editing an answer I wrote before I knew you needed to write a custom type, and had the freedom to just make it implement IComparable. So here's the IComparer approach, which lets you sort objects that don't sort themselves by telling C# how to sort them.

Implement an IComparer that operates over your custom type.

public class ThingieSorter: IComparer<Thingie>{
    public int Compare(Thingie t1, Thingie t2){
        int r = t1.desc.CompareTo(t2);
        if(r != 0){return r;}
        return t1.premium.CompareTo(t2);
    }
}

C# doesn't require IList to implement Sort- it might be inefficient if it's a LinkedList. So let's make a new list, based on arrays, which does sort efficiently, and sort it:

public List<Thingie> sortedOf(IList<Thingie> list){
    List<Thingie> ret = new List<Thingie>(list);
    ret.sort(new ThingieSorter());
    return ret;
}

List<Thingie> implements the interface IList<Thingie>, so replacing your original list with this one shouldn't break anything, as long as you have nothing holding onto the original list and magically expecting it to be sorted. If that's happening, refactor your code so it doesn't grab the reference until after your list has been sorted, since it can't be sorted in place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜