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?

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! That explains it. I also found this article by Marco Russo to relate back to SQL.
Glad to help! Actually, that same article was already linked in my answer.
Ah, OK Justin I see your link. Thanks @Dmitry, will try to search better next time!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.