I have collection of items and every of them has int TypeId
property. I need to reorder items in this collection (or get new), where items are ordered so first all items with TypeId = 3
, then with TypeId = 1
and then TypeId = 2
.
var result = new List<A>();
result.AddRange(source.Where(i => i.TypeId == 3));
result.AddRange(source.Where(i => i.TypeId == 1));
result.AddRange(source.Where(i => i.TypeId == 2));
I wonder, is there any another quick solution without multiple iterating over the source
collection (may be some LINQ trick)?
You can just create an order sequence array and use it in the OrderBy statement by simply asking for the index. Here is the pseudo logic (I can't remember if IndexOf is available with native array, but if not just use another collection type)
int[] order = new int[] { 3, 1, 2};
source.OrderBy(i => Array.IndexOf(order, i.TypeId));
-- EDITED the example based on comment from Luke so that it will compile correctly
精彩评论