5

Possible Duplicate:
How do I get a distinct, ordered list of names from a DataTable using LINQ?

This is my first question here. I am getting a list of distinct values for a drop-down list from my database like so:

var plocQ = (from m in db.SERVICE_NRS
             orderby m.PLOC
             select new { PlocID = m.PLOC, value = m.PLOC }).Distinct();

The ordering seems to have no effect, I have to do this:

var plocQ = (from m in db.SERVICE_NRS
             select new { PlocID = m.PLOC, value = m.PLOC }).Distinct();

plocQ = from s in plocQ
        orderby s.PlocID
        select s;

I am wondering if this has something to do with LINQ or the database? I am a bit new to LINQ and have written too much SQL before. Any ideas?

Community
  • 1
  • 1
CyMark
  • 85
  • 6

1 Answers1

8

It's because you're changing what's in your projection after you sort the initial results. Distinct doesn't guarantee that the order is preserved.

Incidentally, even if it did work that way, you still wouldn't want to! You'd be sorting through the whole list of items, even though some of them were just going to be thrown out.

If you just want to do this all in one statement, you can do this:

var plocQ = (from m in db.SERVICE_NRS
             select new { PlocID = m.PLOC, value = m.PLOC })
            .Distinct()
            .OrderBy(s => s.PlocID);
Justin Morgan
  • 27,557
  • 11
  • 71
  • 100
  • Thanks! That explains it. I also found this article by [Marco Russo](http://programminglinq.com/blogs/marcorusso/archive/2008/07/20/use-of-distinct-and-orderby-in-linq.aspx) to relate back to SQL. – CyMark Aug 05 '11 at 21:37
  • Glad to help! Actually, that same article was already linked in my answer. – Justin Morgan Aug 05 '11 at 21:46
  • Ah, OK Justin I see your link. Thanks @Dmitry, will try to search better next time! – CyMark Aug 05 '11 at 21:52