如何选择数据表中列的不同行数?

时间:2013-08-14 21:43:40

标签: c# linq ado.net datatable

我有一个数据表:

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

有人可以帮我一把吗?

2 个答案:

答案 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");

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

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