Custom sorting with LINQ

前端 未结 6 1175
被撕碎了的回忆
被撕碎了的回忆 2021-01-15 04:16

It seems that i\'m missing something trivial.

Anyway, here it goes:

var order = new[]{1,3,2};
var foos = new[]{new Foo{Id=1}, new Foo{Id=2}, new Fo         


        
6条回答
  •  佛祖请我去吃肉
    2021-01-15 04:25

    I'd probably use a Dictionary of id/ordering pairs to make the order lookup O(1) if I had a lot of these to do. Note that you would also need to handle cases where your values are missing from the ordering -- I chose to move them to the end.

    var order = new Dictionary();
    order.Add( 1, 1 );
    order.Add( 2, 3 );
    order.Add( 3, 2 );
    
    var orderedFoos = foos.OrderBy( f => order.Contains(f.Id) ? order[f.Id] : int.MaxValue );
    

提交回复
热议问题