LINQ的自定义排序 [英] Custom sorting with LINQ
问题描述
我似乎失去了一些东西微不足道。
It seems that i'm missing something trivial.
总之,这里有云:
var order = new[]{1,3,2};
var foos = new[]{new Foo{Id=1}, new Foo{Id=2}, new Foo{Id=3}};
如何使用LINQ按订单阵列FOOS排序?
How to sort foos by order array using Linq?
期望的结果:
foos == new[]{new Foo{Id=1}, new Foo{Id=3}, new Foo{Id=2}};
编辑:
命令包含富IDS 。抱歉,我没有提到。有时候问的问题比正确回答却更难。 :)
Order contains Foo ids. Sorry that i didn't mention that. Sometimes it's even harder to ask question properly than to answer it. :)
推荐答案
好吧,这个问题似乎并没有要的完全的我清楚,所以我会尽力澄清我的认为的你问:
Okay, the question doesn't seem to be entirely clear to me, so I'll try to clarify what I think you're asking:
- 您有ID序列,所需顺序
- 您有对象的集合,的不按正确的顺序的,而是用相应的ID
- 你想获得对象的集合在同一顺序的ID序列
- 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
正确?
这将是:
var orderedFoos = from orderedId in order
join foo in foos on orderedId equals foo.Id into groups
select groups.Single();
您需要一个加入到...
验证您没有任何丢失或 FOOS
重复的ID。它不会,但是,检测,如果你已经在订单
有遗漏或重复的ID。如果你知道,一切都将是正确的(即会有顺序
和反之亦然),那么一个简单的连接是好的: FOOS
只有一个条目每个条目
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);
这篇关于LINQ的自定义排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!