Home > Net >  Entity Framework Core Order By
Entity Framework Core Order By

Time:09-24

I want to retrieve data from a database from a specific column sorted by the column, plus distinct. The data is also fetched distinctly, but not sorted. My query looks like this:

 return context.TableName.OrderBy(l => l.ColumnName).Select(p => p.ColumnName)
            .Distinct().ToList();

CodePudding user response:

Distinct itself discards ordering. It is because of realisation and it depends on Database. So do ordering after Distinct.

return context.TableName
   .Select(p => p.ColumnName)
   .Distinct()
   .OrderBy(l => l)
   .ToList();

CodePudding user response:

Just figured it out myself, distinct must be at the very end of the returns.

return context.TableName.OrderBy(l => l.ColumnName).Select(p => p.ColumnName)
        .ToList().Distinct();
  • Related