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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With