views:

79

answers:

3

Hello

Im trying to make a special orderby with Linq. It has to order by S then P then NB then V and then NC. Im not sure if its the best way to de this but this is what i have:

repeater.DataSource = query.OrderBy(p => p.Title ?).ThenBy(?).ThenBy(?);

+4  A: 

You should use OrderBy<TSource, TKey>(IEnumerable<TSource>, Func<TSource, TKey>, IComparer<TKey>) signature and write your own comparer for this case.

Eugene Cheverda
and im still blank - could you write an example or give a little more guidance?
Buckley
Note that this will not work when dealing with LINQ to Expression trees (LINQ to SQL, LINQ to Entities, NHibernate LINQ, etc). Still +1.
Steven
+4  A: 

If you only have those distinct values in the field, then you can just use a dictionary to translate the strings into suitable numbers, like this:

var order = new Dictionary<string, int>();
order.Add("S", 0);
order.Add("P", 1);
order.Add("NB", 2);
order.Add("V", 3);
order.Add("Nc", 4);
repeater.DataSource = query.OrderBy(p => order[p.Title]);

If the source is LINQ to SQL, you would have to realise it into a list first, so that you are using LINQ to Objects to do the sorting:

repeater.DataSource = query.ToList().OrderBy(p => order[p.Title]);
Guffa
+1. Good idea with the sorting.
Jaroslav Jandek
+1  A: 
query.OrderBy(p => p.Title, new MySpecialComparer());

public class MySpecialComparer : IComparer<string>
{
    private static Dictionary<string, int> parser = new Dictionary<string, int>();

    static MySpecialComparer()
    {
      parser.Add("S", 0);
      parser.Add("P", 1);
      parser.Add("NB", 2);
      parser.Add("V", 3);
      parser.Add("NC", 4);
    }


    public int Compare(string x, string y)
    {
        return parser[x] - parser[y];
    }
}
Jaroslav Jandek
This gives me a "Unsupported overload used for query operator 'OrderBy'."
Buckley
@Buckley: It works for me. Are you using Linq to SQL? What is the type of `query`?
Jaroslav Jandek
Its Linq to Sql yes and query is just a normal query like: var query = from p in dc.Products select p;
Buckley
@Buckley: I'm afraid `IComparer` won't work for an SQL query. Try what `Guffa` suggested.
Jaroslav Jandek
Okay thanks for the help!
Buckley