C# 如何使用 LINQ 从 DataTable 中获取不同的、有序的名称列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/59/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 10:28:31  来源:igfitidea点击:

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

提问by Bob

I have a DataTablewith a Namecolumn. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order byclause.

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

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

Why does the orderbynot get enforced?

为什么不orderby执行?

采纳答案by a7drew

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

为了使其更具可读性和可维护性,您还可以将其拆分为多个 LINQ 语句。

  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 x1into x2, using whatever distinction you require
  3. Finally, create an ordered list, from x2into x3, sorting by whatever you desire
  1. 首先,将您的数据选择到一个新列表中,我们称之为x1,如果需要,进行投影
  2. 接下来,使用您需要的任何区别创建一个不同的列表 from x1intox2
  3. 最后,创建一个有序列表, from x2into x3,按你想要的排序

回答by Bob

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

问题是 Distinct 运算符不保证它会保持值的原始顺序。

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

回答by Nick Berardi

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.

这应该适合您的需要。

回答by a7drew

var sortedTable = (from results in resultTable.AsEnumerable()
select (string)results[attributeList]).Distinct().OrderBy(name => name);

回答by Gavin Fang

Try out the following:

尝试以下操作:

dataTable.Rows.Cast<DataRow>().select(dr => dr["Name"].ToString()).Distinct().OrderBy(name => name);

回答by Philip Raath

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

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

OrderBy needs to be the final operation.

OrderBy 需要是最后的操作。

回答by Presto

You can use something like that:

你可以使用这样的东西:

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