我有一个现有的LINQ查询来检索一些项目:
var result = from foo in x.SomeThings
from bar in x.OtherThings
where foo.RefId == bar.RefId
select foo;
x是一个包含三个属性的对象:
List<MyThing> SomeThings
List<MyThing> OtherThings
List<MyStuff> MyStuffs
包含一个也是MyThing的属性。以下是课程概述:
public class X
{
public List<MyThing> SomeThings;
public List<MyThing> OtherThings;
public List<MyStuff> MyStuffs;
}
public class MyThing
{
public int RefId;
}
public class MyStuff
{
public MyThing TheThing;
public DateTime WhenHappened;
}
如何根据匹配的RefId值,根据最早的WhenHappened值对返回的foos进行排序?
答案 0 :(得分:3)
因此,作为mentioned by Eric Lippert,您可以在此处使用Join
运算符,而不是使用SelectMany
来创建完整的笛卡尔积(这是代码示例的最终结果) ),它会表现得更好。
接下来,为了按照它出现的值排序,您需要加入所有三个列表,而不仅仅是前两个。一旦你加入了所有三个序列,订购就很简单了:
var query = from first in x.SomeThings
join second in x.OtherThings
on first.RefId equals second.RefId
join third in x.MyStuffs
on first.RefId equals third.TheThing.RefId
orderby third.WhenHappened
select first;
此查询的结果是它将返回由WhenHappened
的{{1}}属性排序的所有三个序列中的项目。