简体   繁体   English

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

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

I have a DataTable with a Name column.我有一个DataTableName列。 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 语句。

  1. First, select your data into a new list, let's call it x1 , do a projection if desired首先,将您的数据选择到一个新列表中,我们称之为x1 ,如果需要进行投影
  2. Next, create a distinct list, from x1 into x2 , using whatever distinction you require接下来,使用您需要的任何区别创建一个不同的列表,从x1x2
  3. Finally, create an ordered list, from x2 into x3 , sorting by whatever you desire最后,创建一个有序列表,从x2x3 ,按你想要的任何排序
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM