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".
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?
To count the number of different values that are stored in a given column, you simply need to designate the column you pass in to the COUNT function as DISTINCT . When given a column, COUNT returns the number of values in that column. Combining this with DISTINCT returns only the number of unique (and non-NULL) values.
The correct syntax for using COUNT(DISTINCT) is: SELECT COUNT(DISTINCT Column1) FROM Table; The distinct count will be based off the column in parenthesis. The result set should only be one row, an integer/number of the column you're counting distinct values of.
Yes, you can use COUNT() and DISTINCT together to display the count of only distinct rows. SELECT COUNT(DISTINCT yourColumnName) AS anyVariableName FROM yourTableName; To understand the above syntax, let us create a table.
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
:
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();
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
http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With