views:

26

answers:

1

How do I sort the inner collection of an object returned by the entity framework?

public class X
{
   public string Field {get; set;}
   public EntityCollection<Y> Ys {get; set;}
}

public class Y
{
   public string Field {get; set;}
}

from x in entities.Xs
orderby x.Field
select x

Is there a way to modify this LINQ query to return the X objects and also have the Y objects sorted? Or do I have to manually sort the Y list when it comes back?

EDIT:

This code must return a collection of X typed objects, anonymous typing doesn't meet the current project's requirements.

+3  A: 
var sortedList = from x in entities.Xs
                 orderby x.Field
                 select new {
                   Field = x.Field,
                   y = (select y in x.Ys
                        orderby y.Field
                        select y)
                 };

Edited: If you don't want anonymous types then do this:

var sortedList = from x in entities.Xs
                 orderby x.Field
                 select new X {
                   Field = x.Field,
                   y = (select y in x.Ys
                        orderby y.Field
                        select y)
                 };
John Hartsock
I thought about this, but then I would be handing around anonymous types instead of X types. This happens to live in a service layer so I need to the type to remain as X.
Jerod Houghtelling
@Jerod: So `select new X` instead: http://stackoverflow.com/questions/2450536/simple-way-to-return-anonymous-types-to-make-mvc-using-linq-possible/2717690#2717690
BlueRaja - Danny Pflughoeft
@Jerod Danny's comment beat my edit...but anyways, look at my edited answer
John Hartsock
I guess this doesn't work anyways... "Cannot convert source type 'System.Linq.IQorderedEnumerable<Y>' to target type 'System.Data.Objects.DataClasses.EntityCollection<Y>'.
Jerod Houghtelling
@Jerod ....What is this Query For. Some context might help me in assisting you with a solution.
John Hartsock
It seems to me that you may want to be using POCO classes not the EF classes. http://blogs.msdn.com/b/adonet/archive/2009/05/21/poco-in-the-entity-framework-part-1-the-experience.aspx
John Hartsock