Linq to Entities: Union Order

c# entity-framework linq linq-to-entities

Question

I have a problem with EDM model Union select. I have the records in db with uniqe Ids. For example id list: 1, 2, 3, 4, 5, 6, 7, 8, 9

I need to select, for example, record #6 and 2 records before #6 and 2 records past #6. In select result it should be 4,5,6,7,8

I made this next way:

public IQueryable<photos> GetNextPrev(Int64 photoid, string userlogin)
    {
        var p1 = (from m in db.photos
                 where m.id < photoid && m.userlogin == userlogin
                 orderby m.id descending
                 select m).Take(2).Skip(0);
        var p2 = (from m in db.photos
                  where m.id >= photoid && m.userlogin == userlogin
                  orderby m.id descending
                  select m).Take(3).Skip(0);
        return (p1.Union(p2));
    }

But the ordering is not like in the example...

Thanks for the help!

1
5
5/3/2011 3:11:27 PM

Accepted Answer

It's because of the latter Union, you cannot guarantee order with it. You want to do this on your return:

return (p1.Union(p2).OrderByDescending(m => m.id));

Update

With further understanding of the issues, I think this will take care of it:

public IQueryable<photos> GetNextPrev(Int64 photoid, string userlogin)
{
    var p1 = (from m in db.photos
             where m.id < photoid && m.userlogin == userlogin
             orderby m.id descending
             select m).Take(2).Skip(0);
    var p2 = (from m in db.photos
              where m.id >= photoid && m.userlogin == userlogin
              orderby m.id 
              select m).Take(3).Skip(0);
    return (p1.Union(p2).OrderBy(m => m.id));
}
3
5/3/2011 3:03:25 PM

Popular Answer

You can't assume any ordering. You always need an OrderBy if you want things ordered.

return p1.Union(p2).OrderBy(p=> p.id);


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow