Steven Zack
Steven Zack

Reputation: 5104

Why my orderby method in linq does not work?

I want to query distinct state names in a datatable called ZipTable, and use alpha-beta order to list the state name, but it does not work. Did I miss something?

public List<String> GetAllStates()
{
    ZipTableDataContext dc = new ZipTableDataContext(_connString);
    List<String> query = (from z in dc.ZipTables
                          orderby z.State
                          select z.State).Distinct().ToList();
    return query;
}

Upvotes: 2

Views: 368

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564353

The call to Distinct() will undo your ordering, since it does not preserve the input sequence order. You need to perform your OrderBy after the Distinct() call:

List<String> query = dc.ZipTables.Select(z => z.State)
                       .Distinct()
                       .OrderBy(s => s)
                       .ToList();

Upvotes: 7

Related Questions