Bullines
Bullines

Reputation: 5696

Sort Based on Outer Property

I have an existing LINQ query to retrieve some items:

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

x is an object that contains three properties:

  1. List<MyThing> SomeThings
  2. List<MyThing> OtherThings
  3. List<MyStuff> MyStuffs contains a property that is also a MyThing.

Here is an overview of the classes:

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;
}

How can I sort by the returned foos based on the earliest value of WhenHappened, based on matching RefId values?

Upvotes: 2

Views: 106

Answers (1)

Servy
Servy

Reputation: 203802

So, as mentioned by Eric Lippert, you can use the Join operator here, rather than using SelectMany to do a full Cartesian Product (which is what the end result of your code sample does), and it will perform a lot better.

Next, in order to order by the value it appears you need to join all three lists, rather than just the first two. Once you've joined all three sequences the ordering is quite simple:

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.

Upvotes: 3

Related Questions