[英]C# Linq How to select the distinct row count of multiple columns in a datatable
I have a datatable with multiple key columns (key1, key2, ..., keyN).我有一个包含多个键列(key1、key2、...、keyN)的数据表。 I want to count the distinct key combinations in the table, that match a certain criteria (IsInError = false).我想计算表中符合特定条件(IsInError = false)的不同组合键。
Basically i want to perform the query基本上我想执行查询
SELECT COUNT(*) FROM (SELECT DISTINCT key1, key2, ..., keyN FROM TABLE WHERE IsInError = 'false') A 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?但是我将如何使用多个键和一个条件来做呢?
尝试这样的事情:
table.AsEnumerable().Where(v => v.Field<bool>("IsInError") == false).Select(_ => new { key1 = _.key1, key2 = _.key2, ...., keyn=_.keyn }).Distinct().Count();
A group by might be more suited to this scenario. group by 可能更适合这种情况。
It will group the columns into distinct rows and return a count if desired.它会将列分组为不同的行,并在需要时返回计数。
ie IE
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.这是未经测试的代码,但应该可以帮助您指明正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.