JAck28
JAck28

Reputation: 907

Linq orderby and distinct

I have a table set up as follows:

Section SectionOrder
Sect1     1 
Sect2     2 
Sect3     3 
Sect3     3 
Sect1     1
Sect2     2

I need to pull out distinct sections in correct section order. Here is the linq that I'm using, but it's not putting them in the correct order for some reason.

var myVar = (from x in context.Documents 
             orderby x.SectionOrder ascending
             select x.Section).Distinct(); 

I then want to be able to loop through myVar and put each item in a list as follows:

foreach (var t in myVar)
        {
             listOfDocTypeSections.Add(t);
        }

Upvotes: 1

Views: 100

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726879

The ordering of OrderBy and Distinct matters: while OrderBy produced an ordered sequence, Distinct doesn't. You need to put Distinct first, and then use OrderBy. However, since you take Distinct on one attribute, and order on the other attribute, you need to do it differently:

var myVar = context
    .Documents
    .GroupBy(x => x => x.Section) // This replaces Distinct()
    .OrderBy(g => g.FirstOrDefault().SectionOrder) // There will be no default
    .Select(g => g.Key);

This approach replaces Distinct with GroupBy, and orders on the first SectionOrder item of a group. You can change this sorting strategy to sort on some other item within the Section, say, Min or Max value of SectionOrder:

var myVar = context
    .Documents
    .GroupBy(x => x => x.Section)
    .OrderBy(g => g.Max(x => x.SectionOrder))
    .Select(g => g.Key);

Upvotes: 1

Related Questions