[英]How do I get a distinct, ordered list of names from a DataTable using LINQ?
I have a DataTable
with a Name
column.我有一个
DataTable
有Name
列。 I want to generate a collection of the unique names ordered alphabetically.我想生成按字母顺序排列的唯一名称的集合。 The following query ignores the order by clause.
以下查询忽略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
没有得到执行?
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 );
To make it more readable and maintainable, you can also split it up into multiple LINQ statements.为了使其更具可读性和可维护性,您还可以将其拆分为多个 LINQ 语句。
x1
, do a projection if desiredx1
,如果需要进行投影x1
into x2
, using whatever distinction you requirex1
到x2
x2
into x3
, sorting by whatever you desirex2
到x3
,按你想要的任何排序var sortedTable = (from results in resultTable.AsEnumerable()
select (string)results[attributeList]).Distinct().OrderBy(name => name);
尝试以下操作:
dataTable.Rows.Cast<DataRow>().select(dr => dr["Name"].ToString()).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. OrderBy 需要是最后的操作。
你可以使用这样的东西:
dataTable.Rows.Cast<DataRow>().GroupBy(g => g["Name"]).Select(s => s.First()).OrderBy(o => o["Name"]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.