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
How do I get a distinct, ordered list of names from a DataTable using LINQ?
提问by Bob
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 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 orderby
not get enforced?
为什么不orderby
执行?
采纳答案by a7drew
To make it more readable and maintainable, you can also split it up into multiple LINQ statements.
为了使其更具可读性和可维护性,您还可以将其拆分为多个 LINQ 语句。
- First, select your data into a new list, let's call it
x1
, do a projection if desired - Next, create a distinct list, from
x1
intox2
, using whatever distinction you require - Finally, create an ordered list, from
x2
intox3
, sorting by whatever you desire
- 首先,将您的数据选择到一个新列表中,我们称之为
x1
,如果需要,进行投影 - 接下来,使用您需要的任何区别创建一个不同的列表 from
x1
intox2
- 最后,创建一个有序列表, from
x2
intox3
,按你想要的排序
回答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"]);