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

RJ.*_*RJ. 7 c# linq datatable ado.net

我有一个数据表:

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);
Run Code Online (Sandbox Code Playgroud)

我想知道DISTINCT COUNT OF COLUMN"RelationshipTypeDescription".

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

int relationshipCount = table.AsEnumerable().Distinct().Count();
Run Code Online (Sandbox Code Playgroud)

有人可以帮我一把吗?

p.s*_*w.g 12

你可以这样做:

int relationshipCount = table
    .AsEnumerable()
    .Select(r => r.Field<string>("RelationshipTypeDescription"))
    .Distinct()
    .Count();
Run Code Online (Sandbox Code Playgroud)

但你可能不需要打电话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();
Run Code Online (Sandbox Code Playgroud)


For*_*cke 5

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

DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "RelationshipTypeDescription");
Run Code Online (Sandbox Code Playgroud)

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

http://msdn.microsoft.com/zh-CN/library/wec2b2e6.aspx