Custom sorting with LINQ

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

    Okay, the question doesn't seem to be entirely clear to me, so I'll try to clarify what I think you're asking:

    • You have a sequence of IDs, in the desired order
    • You have a collection of objects, not in the right order, but with corresponding IDs
    • You want to get the collection of objects in the same order as the ID sequence

    Correct?

    That would be:

    var orderedFoos = from orderedId in order
                      join foo in foos on orderedId equals foo.Id into groups
                      select groups.Single();
    

    You need a join ... into to verify that you don't have any missing or duplicate IDs in foos. It won't, however, detect if you've got missing or duplicate IDs in order. If you know that everything will be correct (i.e. there will be exactly one entry in foos for every entry in order and vice versa) then a simple join is okay:

    var orderedFoos = from orderedId in order
                      join foo in foos on orderedId equals foo.Id
                      select foo;
    

    which can be expressed in dot notation as:

    var orderedFoos = order.Join(foos, order => order, foo => foo.ID, (o, f) => f);
    

提交回复
热议问题