1

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);
        }
JAck28
  • 899
  • 4
  • 15
  • 40

1 Answers1

1

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);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • i'm getting this error with your query: base {System.SystemException} = {"The method 'First' can only be used as a final query operation. Consider using the method 'FirstOrDefault' in this instance instead."} – JAck28 Oct 03 '14 at 15:27
  • @JAck28 That's strange. You can use `FirstOrDefault`, too, because there will always be at least one item there. – Sergey Kalinichenko Oct 03 '14 at 15:29
  • @JAck28 Also you should be able to do `listOfDocTypeSections.AddRange(myVar)` instead of a `foreach` loop. – Sergey Kalinichenko Oct 03 '14 at 15:30
  • The firstordefault() worked! Thanks for pointing out that I can use .AddRange - I didn't know about that. – JAck28 Oct 03 '14 at 15:35