【发布时间】:2019-08-17 06:18:40
【问题描述】:
假设我有这张桌子/IQueryable:
+------+------+------+------------+-------------+
| col1 | col2 | col3 | grouperCol | selectorCol |
+------+------+------+------------+-------------+
| 1 | John | Doe | mail1 | |
| 1 | John | Doe | mail2 | 1 |
| 1 | John | Doe | mail3_x | |
| 2 | Bob | Ross | mail1 | 1 |
| 2 | Bob | Ross | mail2_x | |
| 2 | Bob | Ross | mail3_x | |
| 3 | Jane | Doe | mail1 | |
| 3 | Jane | Doe | mail2 | |
| 3 | Jane | Doe | mail3 | |
+------+------+------+------------+-------------+
我想得到这个结果:
+------+------+------+------------+-------------+
| col1 | col2 | col3 | grouperCol | selectorCol |
+------+------+------+------------+-------------+
| 1 | John | Doe | mail2 | 1 |
| 2 | Bob | Ross | mail1 | 1 |
| 3 | Jane | Doe | mail1 | |
+------+------+------+------------+-------------+
基本上,我需要保留一行,选择 selectorCol 不为空的行或第一行。
如何在 C# 中做到这一点?
我可能需要做类似的事情
var filtered = context.table.GroupBy(x => x.col1).Where(...
但是我已经坚持写得简短了。
我可以用 foreach 或其他东西创建一个新列表,但我想它可以用 1 行来完成?
谢谢!
【问题讨论】:
-
您在寻找 SQL 或 Linq 答案吗?
-
var filters = context.table.Where(x=> x.selectorCol != null).GroupBy(x => x.col1),这样就可以得到所有不为空的寄存器,我不明白你的 OR 条件..
-
在每个组上使用
OrderBy将非空selectorCol排序为第一,然后选择每个组中的第一行。