C# 如何选择数据表中某一列的不同行数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18242830/
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-08-10 11:38:53  来源:igfitidea点击:

How do I select the distinct row count of a column in a data table?

c#linqado.netdatatable

提问by RJ.

I have a data table:

我有一个数据表:

DataTable table = new DataTable();

DataColumn column;

column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "RelationshipTypeDescription";
table.Columns.Add(column);

column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "RelatedContactName";
table.Columns.Add(column);

I want to know the DISTINCT COUNT OF COLUMN "RelationshipTypeDescription".

我想知道列的 DISTINCT 计数“RelationshipTypeDescription”。

I'm not sure how to refer to the column name in this:

我不确定如何在此引用列名:

int relationshipCount = table.AsEnumerable().Distinct().Count();

Can someone give me a hand?

有人可以帮我一把吗?

采纳答案by p.s.w.g

You can do this:

你可以这样做:

int relationshipCount = table
    .AsEnumerable()
    .Select(r => r.Field<string>("RelationshipTypeDescription"))
    .Distinct()
    .Count();

But you probably don't need to call AsEnumerable:

但你可能不需要调用AsEnumerable

int relationshipCount = table
    .Select(r => r.Field<string>("RelationshipTypeDescription"))  // Compiler error: "Cannot convert lambda expression to type 'string' because it is not a delegate type"
    .Distinct()
    .Count();

回答by Forest Kunecke

You can also create a new datatable containing only the distinct values of your table:

您还可以创建一个仅包含表的不同值的新数据表:

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "RelationshipTypeDescription");

More info: https://stackoverflow.com/a/1199956/1822214

更多信息:https: //stackoverflow.com/a/1199956/1822214

http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx

http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx