2

我有一个现有的 LINQ 查询来检索一些项目:

var result = from foo in x.SomeThings
             from bar in x.OtherThings
             where foo.RefId == bar.RefId
             select foo;

x 是一个包含三个属性的对象:

  1. List<MyThing> SomeThings
  2. List<MyThing> OtherThings
  3. 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 的最早值对返回的 foo 进行排序?

4

1 回答 1

3

因此,正如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;

The result of this query is that it will return items that are in all three sequences ordered by the WhenHappened property of MyStuffs.

于 2013-03-05T19:55:53.867 回答