基于外部属性排序
本文关键字:排序 属性 于外部 | 更新日期: 2023-09-27 18:02:29
我有一个现有的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;
}
我如何根据WhenHappened的最早值根据匹配的RefId值对返回的foos进行排序?
所以,正如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;
该查询的结果是,它将返回按MyStuffs
的WhenHappened
属性排序的所有三个序列中的项。