我有一个数据表:
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);
我想知道DISTINCT COUNT OF COLUMN“RelationshipTypeDescription”。
我不确定如何引用此列中的列名:
int relationshipCount = table.AsEnumerable().Distinct().Count();
有人可以帮我一把吗?
答案 0 :(得分:12)
你可以这样做:
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();
答案 1 :(得分:4)
您还可以创建一个仅包含表格的不同值的新数据表:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "RelationshipTypeDescription");