1

I need to represent different types of documents in a logical order. So I have a list of objects with IDs. I need to make a comparer which orders these objects by a "manual" rule. Order by id must be 2,32,5,12,8,43... and so on.

I use LINQ

documents.OrderBy(doc=> doc.Id, new DocumentsComparer<int>());

public class DocumentsComparer<T> : IComparer<int>
{
    ...???...
}

How to make such comparer?

podeig
  • 2,597
  • 8
  • 36
  • 60

1 Answers1

2
public class DocumentsComparer<T> : IComparer<int>
{
    private List<int> order = new List<int>{2, 32, 5, 12, 8, 43};
    public int Compare(int x, int y)
    {
        return order.IndexOf(x).CompareTo(order.IndexOf(y));
    }
}

if x and y can be outside of your known list, you'll have to add checks for that and handle those cases however.

Bala R
  • 107,317
  • 23
  • 199
  • 210
  • 1
    If the 'order' list is big, I suggest using a Dictionary mapping instead. – leppie Jun 16 '11 at 12:58
  • It looks nice. But I can not run this comparer. It is not being called by linq query? I do not understand why. I edited my post. – podeig Jun 16 '11 at 13:13
  • @podeig It will not get called immediately after your use `orderby()`. That's something to do with the way `IEnumerable` works(lazy loading). To test it, you can try `documents.OrderBy(doc=> doc.Id, new DocumentsComparer()).ToList()`; – Bala R Jun 16 '11 at 13:17
  • 1
    I guess you can drop the Generic parameter `` since it's not being used. – Bala R Jun 16 '11 at 13:34