开发者

Ordering Distinct values with LINQ [duplicate]

This question already has answers here: Closed 11 years ago.

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 开发者_JAVA技巧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?


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜