Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an List<> with my custom order which is stored in another List (C#)?

Can anyone help.. I have a generic list like so

    IList<itemTp> itemTps;

itemTp basically is a class (has a number of properties) and one property on this is "code"

I need to be able to sort it an specific order which i have set in another List.

This list is a simple list that lists the order (starting from first to last) like say

code1 code3 code2 code5 (notice it goes from 1 to 3 to 2 to 5 - these are the names, they can be called anything .. the important thing is the order, it doesn't have anything to do with the numbers)

Basically i need ensure the items in itemTp sort according what is present in the other list...

So imagine my Ilist is like this code1,code2,code3,code5 - so once the sort is done in my

       IList<itemTp>

will contain 4 classes that are in order and have the property like code1,code3,code2,code5 (order change)

Any ideas how to do this?

like image 729
mark smith Avatar asked Jul 02 '09 21:07

mark smith


1 Answers

You'll need to create an IComparer that will compare items based on the state of your other list. The advantage of using an IComparer is that you'll be able to build caching logic into your class to avoid repeated IndexOf() lookups if you need that optimization. Also, you'll be able to maintain multiple "other" lists that can be used when appropriate.

class ItemTpComparer : IComparer<itemTp>
{
    private IList<codeTp> otherList;

    public ItemTpComparer(IList<codeTp> otherList)
    {
        this.otherList = otherList;
    }

    public int Compare(itemTp a, itemTp b)
    {
        return otherList.IndexOf(a.Code) - otherList.IndexOf(b.Code);
    }
}

And to perform the sort:

myList.Sort(new ItemTpComparer(otherList));
like image 176
anthony Avatar answered Sep 26 '22 02:09

anthony