Comments:
Posted by
Alex James
@
12 Feb 2009
18:16
Try something like this:
class Program
{
static void Main(string[] args)
{
using (BloggingEntities ctx = new BloggingEntities())
{
var results = from person in ctx.People
select new {Person = person,Blogs = person.Blogs.OrderByDescending(b=>b.ID)};
foreach (var result in results)
{
Func<Blogs,Blogs,Blogs[]> zipper = (Blogs first, Blogs second) => new Blogs[]{first,second};
Console.WriteLine("Name = {0}", result.Person.Firstname);
foreach (var zip in zipper.Zip(result.Blogs, result.Person.Blogs))
{
if (zip[0] != zip[1]) throw new Exception("Both sequences should be in the same order");
Console.WriteLine("\t{0}\t{1}", zip[0].Name, zip[1].Name);
}
}
}
}
}
public static class Utility
{
public static IEnumerable<R> Zip<T, V, R>(this Func<T, V, R> func, IEnumerable<T> sequence1, IEnumerable<V> sequence2)
{
IEnumerator<T> enumerator1 = sequence1.GetEnumerator();
IEnumerator<V> enumerator2 = sequence2.GetEnumerator();
while (enumerator1.MoveNext() && enumerator2.MoveNext())
{
yield return func(enumerator1.Current, enumerator2.Current);
}
enumerator1.Dispose();
enumerator2.Dispose();
}
}
This seems to work. I don't think it is guaranteed anywhere, but it seems as if as a sideeffect of how things are implemented it looks like when sorting "result.Blogs" it also sorts "result.Person.Blogs"
Which means of course your person.Blogs is sorted, and you can discard result.Blogs
As I said use at your own peril though.
Alex