9

我有一个数据表:

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

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

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

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

有人可以帮帮我吗?

4

2 回答 2

15

你可以这样做:

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

但是您可能不需要致电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();
于 2013-08-14T21:46:29.710 回答
6

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

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

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

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

于 2013-08-14T21:51:52.600 回答