0

Table design:

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

In C# (linq), how can 'group by' be done for column1 & column2 so that I can get no duplicate rows and also column3 & column4 data?

Example:

Column1(Primary key) | Column2(Primary key) | Column3 | Column4
----------------------------------------------------------------
1                       s                      2          user1
1                       d                      3          user2
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Satty
  • 47
  • 6
  • The initial table design is invalid. Data in a PK must be unique, while the first and third rows are duplicated in your sample. Grouping by the PK is unnecesary, as it will yield the original data again, given that those are unique. – Alejandro Jan 28 '17 at 22:52
  • @Alejandro actually in this case column1 & column2 combines to act as PK...and this is DataTable at C# end which is required to be sent to DB where it will be duplicate.So you can assume, second table is the actual table in db...that's why i need to 'group by' – Satty Jan 28 '17 at 22:57

1 Answers1

0

As Alejandro has pointed out, grouping on primary keys won't give you any benefit since all keys are by default unique so all results as it as go in.

Ignoring if they are primary keys, you can use something like below to group by on multiple columns

from row in Table
    group row by new
    {
        row.ColumnA,
        row.ColumnB,
        ...
        ...
    } into gcs
    select new {
        ColumnA = gcs.Key.ColumnA,
        ColumnB = gcs.Key.ColumnB,
        ...
        ...
    };
Ali Baig
  • 3,819
  • 4
  • 34
  • 47