Custom sorting with LINQ

前端 未结 6 1153
被撕碎了的回忆
被撕碎了的回忆 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:26

    You can do this using a nested query, but it is quite inefficient with O(n²).

    var result = order.Select(o => foos.Single(f => f.Id == o));
    

    If 'order' may contain ids not present in 'foos', you should use SingleOrDefault(). If foos might contain duplicate ids, you should use First() or FirstOrDefault().

    var result = order
        .Select(o => foos.FirstOrDefault(f => f.Id == o))
        .Select(f => f != null);
    

    Maybe even a join will work, but I am not sure if it preserves the order.

    var result = Enumerable.Join(order, foos, o => o, f => f.Id, (o, f) => f);
    

    As Jon mentioned, the join will only work correctly if the input is well formed in the same way as required by my first suggestion.

提交回复
热议问题