c# - select distinct 只选择单列

标签 c# linq distinct-values

基于这个问题:

[如何使用 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/

相关文章:

c# - 如何在 Meteor 中解密密码

c# - 选择 PCL 配置文件时不针对遗留 .NET 平台的原因

c# - 在 C# ASP.NET 中使用 LINQ 返回接下来的 5 行?

c# - 在 x.Kind = "value"时选择 Top(x)

c# - 联合条件和多个 Where 方法调用之间有区别吗?

Java 流具有多个不同的属性

c# - Entity Framework 核心 : Access parent from child

c# - VSTO 合并单元格

Java 对 String 数组进行排序并返回不同的 Item

MYSQL - 查找列是否具有不同的值..?