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

前端 未结 7 2087
谎友^
谎友^ 2020-12-09 14:40

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

7条回答
  •  误落风尘
    2020-12-09 15:09

    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 );
    

提交回复
热议问题