2

I have a datatable with multiple key columns (key1, key2, ..., keyN). I want to count the distinct key combinations in the table, that match a certain criteria (IsInError = false).

Basically i want to perform the query

SELECT COUNT(*) FROM (SELECT DISTINCT key1, key2, ..., keyN FROM TABLE WHERE IsInError = 'false') A

on the datatable.

I have researched a little and found that for a table containing only one key (and with no 'where') I can do this

DataTable table = new DataTable();

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

But how would I go about doing it with multiple keys and a condition?

2 Answers 2

2

Try something like this:

table.AsEnumerable().Where(v => v.Field<bool>("IsInError") == false).Select(_ => new { key1 = _.key1, key2 = _.key2, ...., keyn=_.keyn }).Distinct().Count();
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! That worked perfectly! I had to modifiy your solution slightly as I am not working with a strongly typed datatable, and IsInError is a bit field. Apart from that it was perfect!
Edited it to suit your answer better.
Thumbs up! :) Thanks
0

A group by might be more suited to this scenario.

It will group the columns into distinct rows and return a count if desired.

i.e.

var groups = table.GroupBy(_ => new {_.Key1, _.Key2, _.KeyN})
                  .Select(_ => new { key = _.Key, count = _.Count());

This is untested code, but should help point you in the correct direction.

1 Comment

Thank you! I will give it a try!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.