基于这个问题:
[如何使用 LINQ 执行 SELECT UNIQUE?
我编写了以下表达式以从包含多列的 dt
数据表中选择具有唯一 OrganizationID
列的行。
var distinctRows = (from DataRow dRow in dt.Rows
select new { col1 = dRow["OrganizationID_int"] }).Distinct();
但是当我在执行表达式后检查 distinctRows
时,它只有 1 列 (col1
) 的记录,而不是包含整列。我担心添加像 col2=...
等表达式可能会被解释为我想在所有这些列上选择不同的。
那么如何在仅对 1 列而不是整列应用唯一过滤器的同时获取整行?
最佳答案
I want the whole rows which satisfy that unique condition with all columns. I want to iterate in the next step.
因此您不想按该字段分组并返回多行之一。您只需要唯一的行。
一种方法是使用 Enumerable.GroupBy
并计算每组中的行数:
var uniqueRows = dt.AsEnumerable()
.GroupBy(r => r.Field<int>("OrganizationID_int"))
.Where(g => g.Count() == 1)
.Select(g => g.First());
关于c# - select distinct 只选择单列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13585095/