如何使用 C# Linq 实现"group by"



表设计:

Column1(Primary key) | Column2(Primary key) | Column3 | Column4
----------------------------------------------------------------
1                       s                      2          user1
1                       d                      3          user2
1                       s                      2          user1

在 C# (linq) 中,如何对 column1 和 column2 进行"分组依据",以便我无法获得重复的行以及 column3 和 column4 数据?

例:

Column1(Primary key) | Column2(Primary key) | Column3 | Column4
----------------------------------------------------------------
1                       s                      2          user1
1                       d                      3          user2

正如 Alejandro 所指出的,对主键进行分组不会给您带来任何好处,因为默认情况下所有键都是唯一的,因此所有结果都随之而来。

忽略它们是否是主键,您可以使用如下所示的内容对多个列进行分组

from row in Table
    group row by new
    {
        row.ColumnA,
        row.ColumnB,
        ...
        ...
    } into gcs
    select new {
        ColumnA = gcs.Key.ColumnA,
        ColumnB = gcs.Key.ColumnB,
        ...
        ...
    };

最新更新