114

我有DataTable一个Name专栏。我想生成按字母顺序排列的唯一名称的集合。以下查询忽略order by子句。

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

为什么不orderby强制执行?

4

7 回答 7

57

问题是 Distinct 运算符不同意它将保持值的原始顺序。

所以你的查询需要像这样工作

var names = (from DataRow dr in dataTable.Rows
             select (string)dr["Name"]).Distinct().OrderBy( name => name );
于 2008-08-01T13:18:37.640 回答
39

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
于 2008-09-04T02:57:27.263 回答
11
var sortedTable = (from results in resultTable.AsEnumerable()
select (string)results[attributeList]).Distinct().OrderBy(name => name);
于 2008-12-05T01:08:22.033 回答
8

尝试以下方法:

dataTable.Rows.Cast<DataRow>().select(dr => dr["Name"].ToString()).Distinct().OrderBy(name => name);
于 2013-04-28T09:27:13.573 回答
3

尝试以下

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

这应该可以满足您的需要。

于 2008-08-07T02:35:28.637 回答
2

你可以使用类似的东西:

dataTable.Rows.Cast<DataRow>().GroupBy(g => g["Name"]).Select(s => s.First()).OrderBy(o => o["Name"]);
于 2018-06-25T10:56:10.077 回答
2

抽象:所有的答案都有一些共同点。

OrderBy 需要是最后的操作。

于 2018-01-30T16:19:51.153 回答