开发者

LINQ .OrderBy single letter then by another letter

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.Ord开发者_如何学CerBy(p => p.Title ?).ThenBy(?).ThenBy(?);


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]);


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


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];
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜