Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi peeps,

i've got an IEnuermerable<customclass> documents, i'm wanting to sort this IEnumerable by a custom order, of TypeId

now i know could do documents.OrderBy(d => d.Type.Id) but i'm dont want it to order 1-5 etc, i would like a custom order of type.Id as following

3,5,2,4,6 (this is a button is being created for these documents, but my boss wishes to have them displayed in this order now)

any help on doing this would be very grateful
Posted

You may use a dictionary to map the Type Ids to your own order criterion, e.g.
C#
Dictionary<int, int> mo = new Dictionary<int,int>{ { 3, 0 }, { 5, 1 }, {2,2}, {4,3}, {6,4} };

Then
C#
documents.OrderBy(d => mo[d.Type.Id])
 
Share this answer
 
Comments
Grant Weatherston 17-Mar-14 9:48am    
Thanks alot this worked perfectly ! just so i can make sure i've understood how this works..
you create the dictionary with key being id, and value of the array position? then do order by the dictionary passing in the key (id) as index it'll search for that key, and brings back value 0,1,2,3,4 and will order by them ?
CPallini 17-Mar-14 12:37pm    
Yes.
You could try to implement a custom IComparer<int>:.
C#
public VerySpecialInt32Comparer : IComparer<int>
{
   public int Compare(int left, int right) {
      int result;
      if (left == right) {
         result = 0;
      }
      if (left == 3) {
         result = 1;
      }
      else if ((left == 5) && (right != 3)) {
         result = 1;
      }
      else if ((left == 2) && ((right != 3) && (right != 5)) {
         result = 1;
      }
      else if ((left == 4) && ((right != 3) && (right != 5) && (right != 2)) {
         result = 1;
      }
      else {
         result = -1;
      }
      return result;
   }
}

Once you defined the IComparer<T> implementation, you will have to use it on a List<int>. Transform your IEnumerable<int> into a List<int> this way:
C#
using System.Linq;

IList<int> list = iEnumVariable.ToList();

Finally use the specific comparer implementation:
C#
list.Sort(new VerySpecialInt32Comparer());


Warning! I took into account that there are only 5 values possible (2, 3, 4, 5 and 6). If there are more of them, this alogorithm will not work; you will have to adapt it to your needs.

Hope this helps. Good luck.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900