How do I get a distinct, ordered list of names from a DataTable using LINQ?

Viewed 26716

I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause.

var names =
    (from DataRow dr in dataTable.Rows
    orderby (string)dr["Name"]
    select (string)dr["Name"]).Distinct();

Why does the orderby not get enforced?

7 Answers

The problem is that the Distinct operator does not grant that it will maintain the original order of values.

So your query will need to work like this

var names = (from DataRow dr in dataTable.Rows
             select (string)dr["Name"]).Distinct().OrderBy( name => name );

To make it more readable and maintainable, you can also split it up into multiple LINQ statements.

  1. First, select your data into a new list, let's call it x1, do a projection if desired
  2. Next, create a distinct list, from x1 into x2, using whatever distinction you require
  3. Finally, create an ordered list, from x2 into x3, sorting by whatever you desire
var sortedTable = (from results in resultTable.AsEnumerable()
select (string)results[attributeList]).Distinct().OrderBy(name => name);

Try the following

var names = (from dr in dataTable.Rows
             select (string)dr["Name"]).Distinct().OrderBy(name => name);

this should work for what you need.

To abstract: all of the answers have something in common.

OrderBy needs to be the final operation.

You can use something like that:

dataTable.Rows.Cast<DataRow>().GroupBy(g => g["Name"]).Select(s => s.First()).OrderBy(o => o["Name"]);
Related